package com.example.show_auto.ui.pages

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.PressInteraction
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.runtime.*
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties as WindowDialogProperties
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.PopupProperties
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import com.example.show_auto.data.Guest
import com.example.show_auto.data.SettingsStorage
import com.example.show_auto.data.Recipe
import com.example.show_auto.data.UltimateDataStorage
import com.example.show_auto.ui.pages.UltimateSkillsState
import com.example.show_auto.viewmodel.MainViewModel
import com.example.show_auto.ui.utils.DeviceCompatibility
import com.example.show_auto.ui.utils.OppoCompatibilityFix
import com.example.show_auto.utils.ChefSkillCalculator
import com.example.show_auto.utils.ChefInteractionCalculator
import com.example.show_auto.ui.theme.getChefBoxCompatibleCardColors
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withStyle
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.floor
import kotlin.math.roundToInt
import kotlin.math.truncate



/**
 * 根据品级计算符文率
 */
private fun getRuneRateByRank(rank: String, selectedChefs: List<com.example.show_auto.data.Chef>, skills: List<com.example.show_auto.data.Skill>): Int {
    // 基础符文率
    val baseRuneRate = when (rank) {
        "神" -> 53
        "传" -> 53
        "特" -> 52
        "优" -> 51
        "可" -> 50
        else -> 50
    }
    
    // 如果品级不是特级及以上，直接返回基础符文率
    if (rank != "特" && rank != "神" && rank != "传") {
        return baseRuneRate
    }
    
    // 计算所有厨师的特殊技能加成总和
    var totalSpecialBonus = 0.0
    
    selectedChefs.forEach { chef ->
        // 获取厨师的基础技能描述
        val baseSkillDesc = if (chef.skill > 0) {
            skills.find { it.skillId == chef.skill }?.desc ?: ""
        } else {
            ""
        }
        
        // 获取厨师的修炼技能描述
        val ultimateSkillDesc = getChefSkillDescriptionForCalculation(chef, skills)
        val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
        
        // 检查是否包含"场上厨师制作特级及以上料理时此料理贵客符文概率+*%"类技能
        val specialSkillPattern = "场上厨师制作特级及以上料理时此料理贵客符文概率\\+(\\d+(?:\\.\\d+)?)%"
        val matchResult = specialSkillPattern.toRegex().find(combinedSkillDesc)
        
        if (matchResult != null) {
            // 提取数值并累加
            val bonusValue = matchResult.groupValues[1].toDoubleOrNull() ?: 0.0
            totalSpecialBonus += bonusValue
            System.out.println("厨师 ${chef.name} 特殊技能加成: +${bonusValue}%")
        }
    }
    
    // 如果有特殊技能加成，累加到基础符文率上
    val finalRuneRate = if (totalSpecialBonus > 0) {
        val result = baseRuneRate + totalSpecialBonus
        System.out.println("品级: $rank, 基础符文率: $baseRuneRate%, 特殊技能加成: +${totalSpecialBonus}%, 最终符文率: ${result}%")
        result.toInt()
    } else {
        System.out.println("品级: $rank, 基础符文率: $baseRuneRate%, 无特殊技能加成")
        baseRuneRate
    }
    
    return finalRuneRate
}

/**
 * 根据品级和厨师组合计算符文率（支持默认全修炼开关）
 */
private fun getRuneRateByRankWithOverride(rank: String, selectedChefs: List<com.example.show_auto.data.Chef>, skills: List<com.example.show_auto.data.Skill>, defaultAllUltimate: Boolean): Int {
    // 基础符文率
    val baseRuneRate = when (rank) {
        "神" -> 53
        "传" -> 53
        "特" -> 52
        "优" -> 51
        "可" -> 50
        else -> 50
    }
    
    // 如果品级不是特级及以上，直接返回基础符文率
    if (rank != "特" && rank != "神" && rank != "传") {
        return baseRuneRate
    }
    
    // 计算所有厨师的特殊技能加成总和
    var totalSpecialBonus = 0.0
    
    selectedChefs.forEach { chef ->
        // 获取厨师的基础技能描述
        val baseSkillDesc = if (chef.skill > 0) {
            skills.find { it.skillId == chef.skill }?.desc ?: ""
        } else {
            ""
        }
        
        // 获取厨师的修炼技能描述（使用override版本，确保未拥有厨师也能正确计算修炼技能）
        val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(chef, skills, defaultAllUltimate)
        val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
        
        // 检查是否包含"场上厨师制作特级及以上料理时此料理贵客符文概率+*%"类技能
        val specialSkillPattern = "场上厨师制作特级及以上料理时此料理贵客符文概率\\+(\\d+(?:\\.\\d+)?)%"
        val matchResult = specialSkillPattern.toRegex().find(combinedSkillDesc)
        
        if (matchResult != null) {
            // 提取数值并累加
            val bonusValue = matchResult.groupValues[1].toDoubleOrNull() ?: 0.0
            totalSpecialBonus += bonusValue
            System.out.println("厨师 ${chef.name} 特殊技能加成: +${bonusValue}%")
        }
    }
    
    // 如果有特殊技能加成，累加到基础符文率上
    val finalRuneRate = if (totalSpecialBonus > 0) {
        val result = baseRuneRate + totalSpecialBonus
        System.out.println("品级: $rank, 基础符文率: $baseRuneRate%, 特殊技能加成: +${totalSpecialBonus}%, 最终符文率: ${result}%")
        result.toInt()
    } else {
        System.out.println("品级: $rank, 基础符文率: $baseRuneRate%, 无特殊技能加成")
        baseRuneRate
    }
    
    return finalRuneRate
}

/**
 * 根据星级和份数计算实际贵客率
 */
private fun calculateActualGuestRate(starLevel: Int, quantity: Int, baseGuestRate: Double = 100.0): Double {
    // 检查最低份数要求
    val minQuantity = when (starLevel) {
        1 -> 20
        2 -> 15
        3 -> 12
        4 -> 10
        5 -> 7
        else -> 7 // 默认使用5星要求
    }
    
    // 如果份数不满足最低要求，返回0
    if (quantity < minQuantity) {
        return 0.0
    }
    
    // 按照jisuan文件的逻辑计算实际贵客率
    val actualRate = when (starLevel) {
        1 -> (0.05 + (quantity - 20) * 0.013) * (100 + baseGuestRate)
        2 -> (0.08 + (quantity - 15) * 0.02) * (100 + baseGuestRate)
        3 -> (0.083 + (quantity - 12) * 0.016) * (100 + baseGuestRate)
        4 -> (0.1142 + (quantity - 10) * 0.0059) * (100 + baseGuestRate)
        5 -> (0.1006 + (quantity - 7) * 0.0084) * (100 + baseGuestRate)
        else -> (0.1006 + (quantity - 7) * 0.0084) * (100 + baseGuestRate) // 默认使用5星公式
    }
    
    // 按照jisuan文件的逻辑：截断取整后除以100
    return truncate(actualRate * 100.0) / 100.0
}

/**
 * 格式化数字，去掉末尾的0
 * @param value 要格式化的数字
 * @param maxDecimalPlaces 最大小数位数
 * @return 格式化后的字符串
 */
private fun formatNumber(value: Double, maxDecimalPlaces: Int = 2): String {
    val formatted = String.format("%.${maxDecimalPlaces}f", value)
    return if (formatted.contains('.')) {
        formatted.trimEnd('0').trimEnd('.')
    } else {
        formatted
    }
}

/**
 * 从技能描述中提取暴击率数值
 */
fun extractCritRateFromSkill(skillDesc: String): Double {
    var totalCritRate = 0.0
    
    // 稀有客人赠礼数量X%概率提升X% - 只计算第一个值
    val giftQuantityPattern = "稀有客人赠礼数量(\\d+(?:\\.\\d+)?)%概率提升(\\d+(?:\\.\\d+)?)%".toRegex()
    val giftQuantityMatches = giftQuantityPattern.findAll(skillDesc)
    for (match in giftQuantityMatches) {
        val probability = match.groupValues[1].toDoubleOrNull() ?: 0.0
        totalCritRate += probability // 只计算第一个值，不乘以概率提升
        break // 只取第一个匹配项
    }
    
    // 每制作一种神级料理贵客赠礼翻倍概率+*% (值*3)
    val divineRecipePattern = "每制作一种神级料理贵客赠礼翻倍概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
    val divineRecipeMatches = divineRecipePattern.findAll(skillDesc)
    for (match in divineRecipeMatches) {
        val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
        totalCritRate += value * 3 // 按您要求，这类技能值*3
        break // 只取第一个匹配项
    }
    
    // 贵客赠礼数量*%概率提升*% - 只计算第一个值
    val guestGiftPattern = "贵客赠礼数量(\\d+(?:\\.\\d+)?)%概率提升(\\d+(?:\\.\\d+)?)%".toRegex()
    val guestGiftMatches = guestGiftPattern.findAll(skillDesc)
    for (match in guestGiftMatches) {
        val probability = match.groupValues[1].toDoubleOrNull() ?: 0.0
        totalCritRate += probability // 只计算第一个值，不乘以概率提升
        break // 只取第一个匹配项
    }
    
    return totalCritRate
}

/**
 * 计算厨师的总暴击率（用于厨师选择弹窗和详情显示）
 */
fun calculateTotalCritRate(chef: com.example.show_auto.data.Chef, skills: List<com.example.show_auto.data.Skill>, gameData: com.example.show_auto.data.GameData?, personalData: com.example.show_auto.data.PersonalData?, defaultAllUltimate: Boolean = false): Double {
    var totalCritRate = 0.0
    
    // 1. 计算基础技能暴击率
    if (chef.skill > 0) {
        val baseSkill = skills.find { it.skillId == chef.skill }
        if (baseSkill != null) {
            totalCritRate += extractCritRateFromSkill(baseSkill.desc)
        }
    }
    
    // 2. 计算修炼技能暴击率
    val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(chef, skills, defaultAllUltimate)
    totalCritRate += extractCritRateFromSkill(ultimateSkillDesc)
    
    // 3. 计算厨具暴击率
    val personalChef = personalData?.chefs?.get(chef.chefId)
    if (personalChef?.equip != null && gameData != null) {
        val equip = gameData.equips.find { it.equipId == personalChef.equip.toString() }
        if (equip != null) {
            // 检查厨师是否有厨具技能效果翻倍技能
            val hasEquipSkillMultiplier = hasEquipSkillMultiplier(chef, skills)
            val multiplier = if (hasEquipSkillMultiplier) 2.0 else 1.0
            
            for (skillId in equip.skill) {
                val skill = skills.find { it.skillId == skillId }
                if (skill != null) {
                    totalCritRate += extractCritRateFromSkill(skill.desc) * multiplier
                }
            }
        }
    }
    
    return totalCritRate
}

/**
 * 计算厨师的总暴击率（用于计算结果card，保持原来的计算逻辑）
 */
fun calculateTotalCritRateForCalculator(chef: com.example.show_auto.data.Chef, skills: List<com.example.show_auto.data.Skill>, gameData: com.example.show_auto.data.GameData?, personalData: com.example.show_auto.data.PersonalData?, defaultAllUltimate: Boolean = false): Double {
    var totalCritRate = 100.0 // 默认从100开始
    
    // 1. 计算基础技能暴击率
    if (chef.skill > 0) {
        val baseSkill = skills.find { it.skillId == chef.skill }
        if (baseSkill != null) {
            totalCritRate += extractCritRateFromSkillForCalculator(baseSkill.desc)
        }
    }
    
    // 2. 计算修炼技能暴击率
    val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(chef, skills, defaultAllUltimate)
    totalCritRate += extractCritRateFromSkillForCalculator(ultimateSkillDesc)
    
    // 3. 计算厨具暴击率
    val personalChef = personalData?.chefs?.get(chef.chefId)
    if (personalChef?.equip != null && gameData != null) {
        val equip = gameData.equips.find { it.equipId == personalChef.equip.toString() }
        if (equip != null) {
            // 检查厨师是否有厨具技能效果翻倍技能
            val hasEquipSkillMultiplier = hasEquipSkillMultiplier(chef, skills)
            val multiplier = if (hasEquipSkillMultiplier) 2.0 else 1.0
            
            for (skillId in equip.skill) {
                val skill = skills.find { it.skillId == skillId }
                if (skill != null) {
                    totalCritRate += extractCritRateFromSkillForCalculator(skill.desc) * multiplier
                }
            }
        }
    }
    
    return totalCritRate
}

/**
 * 从技能描述中提取暴击率数值（用于计算结果card，保持原来的计算逻辑）
 */
fun extractCritRateFromSkillForCalculator(skillDesc: String): Double {
    var totalCritRate = 0.0
    
    // 稀有客人赠礼数量X%概率提升X% - 保持原来的计算逻辑
    val giftQuantityPattern = "稀有客人赠礼数量(\\d+(?:\\.\\d+)?)%概率提升(\\d+(?:\\.\\d+)?)%".toRegex()
    val giftQuantityMatches = giftQuantityPattern.findAll(skillDesc)
    for (match in giftQuantityMatches) {
        val probability = match.groupValues[1].toDoubleOrNull() ?: 0.0
        val boost = match.groupValues[2].toDoubleOrNull() ?: 0.0
        totalCritRate += probability * boost / 100.0 // 保持原来的计算逻辑
    }
    
    // 每制作一种神级料理贵客赠礼翻倍概率+*% (值*3)
    val divineRecipePattern = "每制作一种神级料理贵客赠礼翻倍概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
    val divineRecipeMatches = divineRecipePattern.findAll(skillDesc)
    for (match in divineRecipeMatches) {
        val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
        totalCritRate += value * 3 // 按您要求，这类技能值*3
    }
    
    // 贵客赠礼数量*%概率提升*% - 保持原来的计算逻辑
    val guestGiftPattern = "贵客赠礼数量(\\d+(?:\\.\\d+)?)%概率提升(\\d+(?:\\.\\d+)?)%".toRegex()
    val guestGiftMatches = guestGiftPattern.findAll(skillDesc)
    for (match in guestGiftMatches) {
        val probability = match.groupValues[1].toDoubleOrNull() ?: 0.0
        val boost = match.groupValues[2].toDoubleOrNull() ?: 0.0
        totalCritRate += probability * boost / 100.0 // 保持原来的计算逻辑
    }
    
    return totalCritRate
}

/**
 * 检查厨师是否有"每制作一种神级料理贵客赠礼翻倍概率+*%"技能
 * @param chef 厨师数据
 * @param skills 技能数据列表
 * @return 是否有该类技能
 */
private fun hasDivineRecipeSkill(chef: com.example.show_auto.data.Chef, skills: List<com.example.show_auto.data.Skill>): Boolean {
    // 获取基础技能描述
    val baseSkillDesc = if (chef.skill > 0) {
        skills.find { it.skillId == chef.skill }?.desc ?: ""
    } else {
        ""
    }
    
    // 获取修炼技能描述（支持默认全修炼设置）
    val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(chef, skills, true)
    
    // 合并厨师技能描述
    val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
    
    // 检查是否包含"每制作一种神级料理贵客赠礼翻倍概率+*%"技能
    val hasDivineSkill = combinedSkillDesc.contains("每制作一种神级料理贵客赠礼翻倍概率")
    
    // 调试信息：输出厨师技能检测结果
    if (hasDivineSkill) {
        System.out.println("检测到神级料理技能厨师: ${chef.name}")
        System.out.println("  基础技能: $baseSkillDesc")
        System.out.println("  修炼技能: $ultimateSkillDesc")
        System.out.println("  合并技能: $combinedSkillDesc")
    }
    
    return hasDivineSkill
}

/**
 * 贵客率计算器页面
 * 用于查询符文信息和相关菜谱，以及计算贵客率
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun GuestRateCalculatorPage(
    viewModel: MainViewModel,
    onMenuClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    val gameData by viewModel.gameData.collectAsState()
    val uiState by viewModel.uiState.collectAsState()
    val filteredRecipes by viewModel.filteredRecipes.collectAsState()
    val runeRecipes by viewModel.runeRecipes.collectAsState()
    val isLoadingRuneRecipes by viewModel.isLoadingRuneRecipes.collectAsState()
    
    val context = LocalContext.current
    val settingsStorage = remember { SettingsStorage(context) }
    val ultimateStorage = remember { UltimateDataStorage(context) }
    var ultimateSkills by remember { mutableStateOf(UltimateSkillsState()) }
    var recipeLimits by remember { mutableStateOf(com.example.show_auto.ui.pages.RecipeLimitsState()) }
    
    // 菜谱筛选状态
    var onlyShowOwnedRecipes by remember { mutableStateOf(settingsStorage.getFilterOwnedRecipes()) }
    
    // 全局的光环厨师设置状态
    var globalEnabledAuraChefs by remember { mutableStateOf(settingsStorage.getSelectedAuraChefs()) }
    
    // 心法盘默认满级设置状态
    var defaultMaxLevelAmber by remember { mutableStateOf(settingsStorage.getCalculatorDefaultMaxLevelAmber()) }
    
    // 默认全修炼设置状态
    var currentDefaultAllUltimate by remember { mutableStateOf(settingsStorage.getCalculatorDefaultAllUltimate()) }
    
    // 使用个人数据设置状态
    var usePersonalData by remember { mutableStateOf(settingsStorage.getCalculatorUsePersonalData()) }
    
    // 使用全部厨师设置状态
    var useAllChefs by remember { mutableStateOf(settingsStorage.getCalculatorUseAllChefs()) }
    
    // 实时监听心法盘默认满级设置变化，确保主界面显示立即更新
    LaunchedEffect(Unit) {
        while (true) {
            kotlinx.coroutines.delay(100) // 每100ms检查一次
            val newSetting = settingsStorage.getCalculatorDefaultMaxLevelAmber()
            if (newSetting != defaultMaxLevelAmber) {
                defaultMaxLevelAmber = newSetting
            }
            // 同时监听默认全修炼设置变化
            val newDefaultAllUltimate = settingsStorage.getCalculatorDefaultAllUltimate()
            if (newDefaultAllUltimate != currentDefaultAllUltimate) {
                currentDefaultAllUltimate = newDefaultAllUltimate
            }
            // 同时监听使用个人数据设置变化
            val newUsePersonalData = settingsStorage.getCalculatorUsePersonalData()
            if (newUsePersonalData != usePersonalData) {
                usePersonalData = newUsePersonalData
            }
            // 同时监听使用全部厨师设置变化
            val newUseAllChefs = settingsStorage.getCalculatorUseAllChefs()
            if (newUseAllChefs != useAllChefs) {
                useAllChefs = newUseAllChefs
            }
        }
    }
    
    // 监听gameData变化，自动同步光环厨师设置
    LaunchedEffect(gameData) {
        if (gameData != null) {
            // 当gameData更新时（如导入数据成功后），重新读取可能已更新的光环厨师设置
            globalEnabledAuraChefs = settingsStorage.getSelectedAuraChefs()
            // 同时更新心法盘默认满级设置
            defaultMaxLevelAmber = settingsStorage.getCalculatorDefaultMaxLevelAmber()
            // 同时更新默认全修炼设置
            currentDefaultAllUltimate = settingsStorage.getCalculatorDefaultAllUltimate()
            // 同时更新使用个人数据设置
            usePersonalData = settingsStorage.getCalculatorUsePersonalData()
            // 同时更新使用全部厨师设置
            useAllChefs = settingsStorage.getCalculatorUseAllChefs()
        }
    }
    
    // 加载个人技法数据
    LaunchedEffect(Unit) {
        ultimateStorage.loadUltimateData()?.let { (skills, limits, _) ->
            ultimateSkills = skills
            recipeLimits = limits
        }
    }

    
    var searchQuery by remember { mutableStateOf("") }
    var selectedRunes by remember { mutableStateOf<Set<String>>(emptySet()) }
    var isDropdownExpanded by remember { mutableStateOf(false) }
    var hasQueriedResults by remember { mutableStateOf(false) }
    val interactionSource = remember { MutableInteractionSource() }
    
    // 符文分类筛选状态 - 从设置中读取初始值
    var showGoldRunes by remember { mutableStateOf(settingsStorage.getShowGoldRunes()) }
    var showSilverRunes by remember { mutableStateOf(settingsStorage.getShowSilverRunes()) }
    var showBronzeRunes by remember { mutableStateOf(settingsStorage.getShowBronzeRunes()) }
    
    // 使用说明弹窗状态
    var showUsageDialog by remember { mutableStateOf(false) }
    // 使用说明弹窗的tab状态：0=贵客冲突查询，1=贵客率计算器
    var usageDialogTabIndex by remember { mutableStateOf(0) }
    
    // 设置弹窗状态
    var showSettingsDialog by remember { mutableStateOf(false) }
    
    // 主Tab状态：0=查询贵客冲突，1=贵客率计算器
    var mainTabIndex by remember { mutableStateOf(1) }
    
    // 菜谱显示模式：true=显示全部，false=只显示已拥有
    var showAllRecipes by remember { mutableStateOf(false) }
    
    // 标签页状态：0=无冲突菜谱，1=有冲突菜谱
    var selectedTabIndex by remember { mutableStateOf(0) }
    
    // 最大选择数量提示对话框
    var showMaxSelectionDialog by remember { mutableStateOf(false) }
    
    // 冲突菜谱弹窗状态
    var showConflictDialog by remember { mutableStateOf(false) }
    var conflictDialogRecipe by remember { mutableStateOf<Recipe?>(null) }
    
    // 贵客必来份数限制提示弹窗状态
    var showGuestArrivalLimitDialog by remember { mutableStateOf(false) }
    var guestArrivalLimitInfo by remember { mutableStateOf<GuestArrivalLimitInfo?>(null) }
    
    // 贵客必来份数对照表弹窗状态
    var showGuestPortionTable by remember { mutableStateOf(false) }
    

    
    // 符文菜谱统计信息：符文名 -> (总数, 已拥有数)
    var runeRecipeStats by remember { mutableStateOf<Map<String, Pair<Int, Int>>>(emptyMap()) }
    
    // 符文折叠状态：符文名 -> 是否折叠
    var collapsedRunes by remember { mutableStateOf<Set<String>>(emptySet()) }
    
    // 贵客率计算器的厨师、厨具、菜谱选择状态
    var calculatorSelectedChefs by remember { mutableStateOf<List<com.example.show_auto.data.Chef>>(emptyList()) }
    var calculatorSelectedEquips by remember { mutableStateOf<List<com.example.show_auto.data.Equip>>(emptyList()) }
    var calculatorSelectedRecipes by remember { mutableStateOf<List<com.example.show_auto.data.Recipe>>(emptyList()) }
    
    // 贵客率计算器的心法盘选择状态 - 每个厨师对应3个心法盘
    var calculatorSelectedAmbers by remember { mutableStateOf<List<List<com.example.show_auto.data.Amber?>>>(emptyList()) }
    // 贵客率计算器的等级选择状态 - 每个厨师对应1个等级
    var calculatorSelectedLevels by remember { mutableStateOf<List<Int?>>(emptyList()) }
    
    // 贵客率计算器的星级选择状态
    var calculatorSelectedStarLevel by remember { mutableStateOf(5) } // 默认5星
    
    // 贵客率计算器的品级选择状态
    var calculatorSelectedRank by remember { mutableStateOf("可") } // 默认可级
    
    // 贵客率计算器的份数状态
    var calculatorQuantity by remember { mutableStateOf(7) } // 默认7份
    
    // 一键查询菜谱分配后的份数状态
    var calculatorRecipePortions by remember { mutableStateOf<List<Int>>(List(9) { 0 }) } // 9个菜谱槽位的份数
    var calculatorSelectedPortions by remember { mutableStateOf(7) } // 计算结果中显示的份数（取最大值）
    var isPortionsManuallyModified by remember { mutableStateOf(false) } // 标记用户是否手动修改过份数
    
    // 一键查询相关状态
    var oneClickQueryResult by remember { mutableStateOf<OneClickQueryResult?>(null) }
    var isOneClickQueryInProgress by remember { mutableStateOf(false) }
    
    // 辅助函数：同步更新所有已选择菜谱的槽位份数
    fun updateRecipePortionsForAllSelectedRecipes() {
        val updatedPortions = calculatorRecipePortions.toMutableList()
        var hasChanges = false
        
        for (i in 0 until 9) {
            val recipe = calculatorSelectedRecipes.getOrNull(i)
            if (recipe != null && recipe.name.isNotEmpty()) {
                // 检查该菜谱是否为强补菜谱
                val isSupplementedRecipe = recipe.rarity in 1..2 && 
                    recipe.time <= 300 // 5分钟以内的菜谱
                
                // 如果是强补菜谱，份数保持为1，不参与同步更新
                if (isSupplementedRecipe) {
                    System.out.println("手动修改份数时，槽位$i 菜谱 ${recipe.name} 是强补菜谱，份数保持为1")
                    continue
                }
                
                // 如果该槽位有菜谱，更新份数
                if (updatedPortions[i] != calculatorSelectedPortions) {
                    updatedPortions[i] = calculatorSelectedPortions
                    hasChanges = true
                }
            }
        }
        
        if (hasChanges) {
            calculatorRecipePortions = updatedPortions
            System.out.println("手动修改份数同步更新菜谱槽位份数: ${updatedPortions}")
        }
    }
    
    // 辅助函数：打印厨师选择框中每个厨师的详细信息
    fun printSelectedChefsDetails() {
        if (calculatorSelectedChefs.isEmpty()) {
            System.out.println("=== 厨师选择框状态：未选择任何厨师 ===")
            return
        }
        
        System.out.println("=== 厨师选择框状态：已选择 ${calculatorSelectedChefs.size} 个厨师 ===")
        
        calculatorSelectedChefs.forEachIndexed { index, chef ->
            if (chef.name.isNotEmpty()) {
                System.out.println("--- 厨师 ${index + 1}: ${chef.name} ---")
                
                // 计算并显示贵客率
                val level = calculatorSelectedLevels.getOrNull(index)
                val ambers = calculatorSelectedAmbers.getOrNull(index)
                val equip = calculatorSelectedEquips.getOrNull(index)
                
                val guestRate = calculateTotalGuestRateBonusWithCalculatorData(
                    chef, 
                    gameData?.skills ?: emptyList(), 
                    gameData, 
                    viewModel.personalData.value, 
                    level, 
                    ambers, 
                    equip, 
                    settingsStorage.getCalculatorDefaultAllUltimate()
                )
                System.out.println("  贵客率: ${String.format("%.2f", guestRate)}%")
                
                // 计算并显示暴击率（只取本身的，不加100）
                val critRate = if (equip != null && equip.name.isNotEmpty()) {
                    var totalCritRate = 0.0
                    
                    // 1. 计算基础技能暴击率
                    if (chef.skill > 0) {
                        val baseSkill = gameData?.skills?.find { it.skillId == chef.skill }
                        if (baseSkill != null) {
                            totalCritRate += extractCritRateFromSkillForCalculator(baseSkill.desc)
                        }
                    }
                    
                    // 2. 计算修炼技能暴击率
                    val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(chef, gameData?.skills ?: emptyList(), settingsStorage.getCalculatorDefaultAllUltimate())
                    totalCritRate += extractCritRateFromSkillForCalculator(ultimateSkillDesc)
                    
                    // 3. 计算厨具暴击率
                    // 检查厨师是否有厨具技能效果翻倍技能
                    val hasEquipSkillMultiplier = hasEquipSkillMultiplier(chef, gameData?.skills ?: emptyList())
                    val multiplier = if (hasEquipSkillMultiplier) 2.0 else 1.0
                    
                    for (skillId in equip.skill) {
                        val skill = gameData?.skills?.find { it.skillId == skillId }
                        if (skill != null) {
                            totalCritRate += extractCritRateFromSkillForCalculator(skill.desc) * multiplier
                        }
                    }
                    
                    totalCritRate
                } else {
                    var totalCritRate = 0.0
                    
                    // 1. 计算基础技能暴击率
                    if (chef.skill > 0) {
                        val baseSkill = gameData?.skills?.find { it.skillId == chef.skill }
                        if (baseSkill != null) {
                            totalCritRate += extractCritRateFromSkillForCalculator(baseSkill.desc)
                        }
                    }
                    
                    // 2. 计算修炼技能暴击率
                    val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(chef, gameData?.skills ?: emptyList(), settingsStorage.getCalculatorDefaultAllUltimate())
                    totalCritRate += extractCritRateFromSkillForCalculator(ultimateSkillDesc)
                    
                    totalCritRate
                }
                System.out.println("  暴击率: ${String.format("%.2f", critRate)}%")
                
                // 计算并显示时间加成
                val timeBonus = calculateOpeningTimeBonus(chef, equip, gameData?.skills ?: emptyList(), gameData, viewModel.personalData.value, settingsStorage.getCalculatorDefaultAllUltimate())
                System.out.println("  时间加成: ${String.format("%.2f", timeBonus)}%")
                
                // 计算并显示技法值
                val chefInteraction = com.example.show_auto.utils.ChefInteractionCalculator.calculateChefInteractions(
                    listOf(chef), gameData?.skills ?: emptyList(), globalEnabledAuraChefs
                ).getOrNull(0)
                val enhancedChef = com.example.show_auto.utils.ChefSkillCalculator.applyAllSkills(
                    chef, ultimateSkills, equip, gameData?.skills ?: emptyList(), chefInteraction
                )
                
                // 如果启用厨具遗玉，还需要应用心法盘技法值加成
                val finalEnhancedChef = if (settingsStorage.getCalculatorUsePersonalData() && gameData != null) {
                    val currentGameData = gameData
                    // 获取厨师的心法盘配置（优先使用厨师选择框中的配置）
                    val chefAmbers = if (index < calculatorSelectedAmbers.size && calculatorSelectedAmbers[index].any { it != null }) {
                        // 使用厨师选择框中的心法盘配置
                        calculatorSelectedAmbers[index]
                    } else {
                        // 如果没有厨师选择框配置，使用个人数据中的配置
                        val personalChef = viewModel.personalData.value?.chefs?.get(chef.chefId)
                        if (personalChef?.ambers != null && personalChef.ambers.isNotEmpty()) {
                            val ambers = mutableListOf<com.example.show_auto.data.Amber?>()
                            personalChef.ambers.forEach { amberId ->
                                val amber = currentGameData?.ambers?.find { it.amberId == amberId.toString() }
                                ambers.add(amber)
                            }
                            // 确保有3个位置
                            while (ambers.size < 3) {
                                ambers.add(null)
                            }
                            ambers.take(3)
                        } else {
                            listOf(null, null, null)
                        }
                    }
                    
                    // 获取厨师等级（优先使用厨师选择框中的等级）
                    val chefLevel = if (index < calculatorSelectedLevels.size) calculatorSelectedLevels[index] ?: 1 else 1
                    
                    // 如果开启了心法盘默认满级，则对所有蓝色心法盘位置使用满朋陨
                    val finalAmbers = if (settingsStorage.getCalculatorDefaultMaxLevelAmber()) {
                        applyMaxLevelAmberToBluePositions(chef, chefAmbers.toMutableList(), currentGameData, true)
                    } else {
                        chefAmbers
                    }
                    
                    // 计算心法盘技法值加成
                    val techniqueValuesWithAmbers = calculateTechniqueValuesWithAmbers(chef, currentGameData?.skills ?: emptyList(), currentGameData, chefLevel, finalAmbers, enhancedChef)
                    
                    // 创建包含心法盘加成的最终厨师数据
                    enhancedChef.copy(
                        stirfry = techniqueValuesWithAmbers["stirfry"]?.second ?: enhancedChef.stirfry,
                        boil = techniqueValuesWithAmbers["boil"]?.second ?: enhancedChef.boil,
                        knife = techniqueValuesWithAmbers["knife"]?.second ?: enhancedChef.knife,
                        fry = techniqueValuesWithAmbers["fry"]?.second ?: enhancedChef.fry,
                        bake = techniqueValuesWithAmbers["bake"]?.second ?: enhancedChef.bake,
                        steam = techniqueValuesWithAmbers["steam"]?.second ?: enhancedChef.steam
                    )
                } else {
                    enhancedChef
                }
                
                System.out.println("  技法值: 炒${finalEnhancedChef.stirfry} 煮${finalEnhancedChef.boil} 切${finalEnhancedChef.knife} 炸${finalEnhancedChef.fry} 烤${finalEnhancedChef.bake} 蒸${finalEnhancedChef.steam}")
            }
        }
        
        System.out.println("=== 厨师选择框详细信息打印完成 ===")
    }
    
    // 监听心法盘默认满级设置变化，重新应用已选择厨师的心法盘配置
    LaunchedEffect(defaultMaxLevelAmber) {
        val currentGameData = gameData
        val currentPersonalData = viewModel.personalData.value
        if (currentGameData != null && calculatorSelectedChefs.isNotEmpty()) {
            val updatedAmbers = calculatorSelectedAmbers.toMutableList()
            val updatedLevels = calculatorSelectedLevels.toMutableList()
            
            calculatorSelectedChefs.forEachIndexed { index, chef ->
                if (chef.name.isNotEmpty()) {
                    // 确保列表有足够的位置
                    while (updatedAmbers.size <= index) {
                        updatedAmbers.add(listOf(null, null, null))
                    }
                    while (updatedLevels.size <= index) {
                        updatedLevels.add(null)
                    }
                    
                    val personalChef = currentPersonalData?.chefs?.get(chef.chefId)
                    
                    // 更新心法盘等级
                    updatedLevels[index] = if (defaultMaxLevelAmber) {
                        when (chef.rarity) {
                            5 -> 5
                            4 -> 4
                            else -> 3
                        }
                    } else {
                        // 当心法盘默认满级关闭时，所有厨师的心法盘等级都设置为1级
                        1
                    }
                    
                    // 更新心法盘配置
                    if (defaultMaxLevelAmber) {
                        // 获取当前心法盘配置，如果为空则创建默认配置
                        var currentAmbers = updatedAmbers[index].toMutableList()
                        
                        // 如果当前心法盘配置为空或未正确初始化，则创建默认配置
                        if (currentAmbers.isEmpty() || currentAmbers.all { it == null }) {
                            // 解析厨师的心法盘颜色配置
                            val amberColors = parseChefAmberColors(chef.diskDesc)
                            currentAmbers = mutableListOf()
                            
                            // 根据心法盘颜色创建默认配置
                            amberColors.forEach { color ->
                                when (color) {
                                    "绿" -> {
                                        // 绿色心法盘位置需要从个人数据中获取实际配置
                                        val personalAmber = personalChef?.ambers?.getOrNull(currentAmbers.size)
                                        if (personalAmber != null && currentGameData != null) {
                                            val amber = currentGameData.ambers.find { it.amberId == personalAmber.toString() }
                                            currentAmbers.add(amber)
                                        } else {
                                            currentAmbers.add(null)
                                        }
                                    }
                                    else -> {
                                        // 红色和蓝色心法盘位置先设置为空，后续会应用满朋陨
                                        currentAmbers.add(null)
                                    }
                                }
                            }
                            
                            // 确保有3个位置
                            while (currentAmbers.size < 3) {
                                currentAmbers.add(null)
                            }
                        }
                        
                        // 对所有蓝色心法盘位置使用满朋陨
                        applyMaxLevelAmberToBluePositions(chef, currentAmbers, currentGameData, true)
                        updatedAmbers[index] = currentAmbers
                        
                        // 调试信息：输出心法盘更新信息
                        System.out.println("设置变化触发心法盘更新 - 厨师 ${chef.name}:")
                        System.out.println("  心法盘描述: ${chef.diskDesc}")
                        System.out.println("  最终心法盘配置: $currentAmbers")
                    } else {
                        // 当心法盘默认满级关闭时，保持用户之前选择的心法盘，不清空
                        // 这里不需要做任何改变，保持当前的心法盘选择
                    }
                }
            }
            
            calculatorSelectedAmbers = updatedAmbers
            calculatorSelectedLevels = updatedLevels
        }
    }
    
    // 贵客率计算器的对话框状态
    var calculatorShowChefDialog by remember { mutableStateOf(false) }
    var calculatorShowEquipDialog by remember { mutableStateOf(false) }
    var calculatorShowRecipeDialog by remember { mutableStateOf(false) }
    var calculatorDialogIndex by remember { mutableStateOf(0) } // 0, 1, 2 对应三个心法盘位置
    
    // 同贵客双菜谱展开状态
    var isDualRecipeExpanded by remember { mutableStateOf(false) }
    
    // 心法盘选择框展开状态（默认收起）
    var isAmberSelectionExpanded by remember { mutableStateOf(false) }
    
    // 同贵客双菜谱的状态变量
    var dualRecipeStarLevel1 by remember { mutableStateOf(5) }
    var dualRecipeQuantity1 by remember { mutableStateOf(7) }
    var dualRecipeStarLevel2 by remember { mutableStateOf(5) }
    var dualRecipeQuantity2 by remember { mutableStateOf(7) }
    var dualRecipeGuestRate by remember { mutableStateOf(0.0) }
    

    

    
    // 计算厨师间技法影响
    val chefInteractions = remember(calculatorSelectedChefs, gameData?.skills, globalEnabledAuraChefs) {
        ChefInteractionCalculator.calculateChefInteractions(calculatorSelectedChefs, gameData?.skills ?: emptyList(), globalEnabledAuraChefs)
    }
    
    // 监听输入框点击事件
    LaunchedEffect(interactionSource) {
        interactionSource.interactions.collect { interaction ->
            when (interaction) {
                is PressInteraction.Press -> {
                    isDropdownExpanded = true
                    hasQueriedResults = false
                }
            }
        }
    }
    


    // 符文分类定义
    val goldRunes = remember {
        listOf("恐怖利刃", "鼓风机", "蒸馏杯", "千年煮鳖", "香烤鱼排", "五星炒果")
    }
    val silverRunes = remember {
        listOf("刀嘴鹦鹉", "一昧真火", "蒸汽宝石", "耐煮的水草", "焦虫", "暖石")
    }
    val bronzeRunes = remember {
        listOf("剪刀蟹", "油火虫", "蒸汽耳环", "防水的柠檬", "烤焦的菊花", "五香果")
    }
    
    // 全部符文列表
    val allRunes = remember {
        goldRunes + silverRunes + bronzeRunes
    }
    
    // 当游戏数据加载完成后，计算符文统计信息
    LaunchedEffect(gameData) {
        val currentGameData = gameData
        if (currentGameData != null) {
            val stats = mutableMapOf<String, Pair<Int, Int>>()
            
            allRunes.forEach { rune ->
                // 找到该符文相关的所有菜谱
                val matchingRecipeNames = mutableSetOf<String>()
                currentGameData.guests.forEach { guest ->
                    guest.gifts.forEach { gift ->
                        if (gift.antique == rune) {
                            matchingRecipeNames.add(gift.recipe)
                        }
                    }
                }
                
                val relatedRecipes = currentGameData.recipes.filter { recipe ->
                    matchingRecipeNames.contains(recipe.name)
                }
                
                val totalCount = relatedRecipes.size
                val ownedCount = relatedRecipes.count { it.got }
                stats[rune] = Pair(totalCount, ownedCount)
            }
            
            runeRecipeStats = stats
        }
    }

    // 根据分类筛选和搜索条件过滤符文
    val filteredRunes = remember(searchQuery, selectedRunes, showGoldRunes, showSilverRunes, showBronzeRunes) {
        // 根据分类筛选确定可用符文
        val availableRunes = when {
            showGoldRunes -> goldRunes
            showSilverRunes -> silverRunes
            showBronzeRunes -> bronzeRunes
            else -> allRunes // 没有分类选择时显示所有符文
        }
        
        // 再根据搜索条件过滤
        availableRunes.filter { rune ->
            if (searchQuery.isEmpty()) {
                true // 空搜索时显示所有符文
            } else {
                rune.contains(searchQuery, ignoreCase = true)
            }
        }
    }
    


    // 当选择符文时，触发相应逻辑（暂时不实现具体搜索逻辑）
    LaunchedEffect(selectedRunes) {
        // 多选模式下不自动触发搜索，需要点击一键查询按钮
        // 当符文选择清空时，清除搜索结果
        if (selectedRunes.isEmpty()) {
            viewModel.clearRuneSearch()
            hasQueriedResults = false
        }
    }
    
    OppoCompatibilityFix.FixedLayoutContainer(
        modifier = modifier.fillMaxSize()
    ) {
        // 顶部应用栏
        TopAppBar(
            title = { 
                Row(
                    verticalAlignment = Alignment.CenterVertically
                ) {
                Text(
                        text = "查询符文配置",
                    fontWeight = FontWeight.Medium
                )
                    Spacer(modifier = Modifier.width(8.dp))
                    IconButton(
                        onClick = { 
                            // 根据当前主tab设置使用说明弹窗的初始tab状态
                            usageDialogTabIndex = mainTabIndex
                            showUsageDialog = true 
                        },
                        modifier = Modifier.size(24.dp)
                    ) {
                        Icon(
                            imageVector = Icons.Default.Info,
                            contentDescription = "使用说明",
                            modifier = Modifier.size(20.dp)
                        )
                    }
                }
            },
            navigationIcon = {
                IconButton(onClick = onMenuClick) {
                    Icon(
                        imageVector = Icons.Default.Menu,
                        contentDescription = "菜单"
                    )
                }
            },
            actions = {
                // 移除右上角设置按钮，改为在按钮行中显示
            },
            colors = TopAppBarDefaults.topAppBarColors(
                containerColor = MaterialTheme.colorScheme.primaryContainer,
                titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
                navigationIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer
            )
        )
        
        // 页面内容
        Column(
            modifier = Modifier
                .fillMaxSize()
                .let {
                    if (OppoCompatibilityFix.isProblematicOppoDevice()) {
                        it.verticalScroll(rememberScrollState()).fillMaxSize()
                    } else {
                        it.verticalScroll(rememberScrollState())
                    }
                }
                .padding(OppoCompatibilityFix.getFixedSpacing(16.dp)),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Spacer(modifier = Modifier.height(OppoCompatibilityFix.getFixedSpacing(16.dp)))
            
            // 主Tab切换框
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp),
                shape = RoundedCornerShape(20.dp),
                colors = CardDefaults.cardColors(
                    containerColor = Color(0xFFE3F2FD)
                ),
                elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
            ) {
                Row(
                    modifier = Modifier.padding(4.dp)
                ) {
                    // 查询贵客冲突标签
                    Surface(
                        onClick = { mainTabIndex = 0 },
                        modifier = Modifier
                            .weight(1f)
                            .height(28.dp),
                        shape = RoundedCornerShape(16.dp),
                        color = if (mainTabIndex == 0) {
                            MaterialTheme.colorScheme.primary
                        } else {
                            Color.Transparent
                        }
                    ) {
                        Box(
                            modifier = Modifier.fillMaxSize(),
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = "查询贵客冲突",
                                fontSize = 12.sp,
                                fontWeight = FontWeight.Medium,
                                color = if (mainTabIndex == 0) {
                                    Color.White
                                } else {
                                    MaterialTheme.colorScheme.primary
                                }
                            )
                        }
                    }
                    
                    Spacer(modifier = Modifier.width(4.dp))
                    
                    // 贵客率计算器标签
                    Surface(
                        onClick = { mainTabIndex = 1 },
                        modifier = Modifier
                            .weight(1f)
                            .height(28.dp),
                        shape = RoundedCornerShape(16.dp),
                        color = if (mainTabIndex == 1) {
                            MaterialTheme.colorScheme.primary
                        } else {
                            Color.Transparent
                        }
                    ) {
                        Box(
                            modifier = Modifier.fillMaxSize(),
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = "贵客率计算器",
                                fontSize = 12.sp,
                                fontWeight = FontWeight.Medium,
                                color = if (mainTabIndex == 1) {
                                    Color.White
                                } else {
                                    MaterialTheme.colorScheme.primary
                                }
                            )
                        }
                    }
                }
            }
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 根据选择的主Tab显示不同内容
            when (mainTabIndex) {
                0 -> {
                    // 查询贵客冲突页面
            // 符文搜索区域
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 符文搜索框
                Box(modifier = Modifier.weight(1f)) {
                    OutlinedTextField(
                        value = if (selectedRunes.isNotEmpty()) {
                            "已选择${selectedRunes.size}个符文"
                        } else {
                            searchQuery
                        },
                        onValueChange = { value ->
                            if (selectedRunes.isEmpty()) {
                                searchQuery = value
                                isDropdownExpanded = value.isNotEmpty() || filteredRunes.isNotEmpty()
                            }
                        },
                        label = { Text("选择符文") },
                        placeholder = { Text("输入符文名称搜索", fontSize = 12.sp) },
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable(
                                interactionSource = interactionSource,
                                indication = null
                            ) { },
                        leadingIcon = {
                            Icon(
                                imageVector = Icons.Default.Search,
                                contentDescription = "搜索"
                            )
                        },
                        trailingIcon = {
                            if (selectedRunes.isNotEmpty()) {
                                IconButton(
                                    onClick = {
                                        selectedRunes = emptySet()
                                        searchQuery = ""
                                        isDropdownExpanded = false
                                        hasQueriedResults = false
                                        showAllRecipes = false
                                        viewModel.clearSelection()
                                        viewModel.clearRuneSearch()
                                    }
                                ) {
                                    Icon(
                                        imageVector = Icons.Default.Clear,
                                        contentDescription = "清除"
                                    )
                                }
                            } else {
                                IconButton(
                                    onClick = {
                                        isDropdownExpanded = !isDropdownExpanded
                                    }
                                ) {
                                Icon(
                                    imageVector = if (isDropdownExpanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
                                        contentDescription = if (isDropdownExpanded) "收起" else "展开"
                                )
                                }
                            }
                        },
                        singleLine = true,
                        colors = OppoCompatibilityFix.getFixedTextFieldColors(),
                        interactionSource = interactionSource
                    )
                }
                
                // 一键查询按钮
                Button(
                    onClick = {
                        if (selectedRunes.isNotEmpty()) {
                            // 执行多符文查询逻辑
                            System.out.println("符文查询区域一键查询按钮被点击")
                            
                            // 打印厨师选择框中每个厨师的详细信息
                            printSelectedChefsDetails()
                            
                            viewModel.searchRecipesByMultipleRunes(selectedRunes.toList())
                            // 隐藏下拉框并标记已查询
                            isDropdownExpanded = false
                            hasQueriedResults = true
                        }
                    },
                    modifier = Modifier
                        .height(56.dp)
                        .padding(top = 5.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.primary,
                        contentColor = MaterialTheme.colorScheme.onPrimary
                    ),
                    shape = RoundedCornerShape(8.dp),
                    enabled = selectedRunes.isNotEmpty()
                ) {
                    Text(
                        "一键查询",
                        fontSize = 12.sp,
                        fontWeight = FontWeight.Medium
                    )
                }
            }
            
            // 已选择的符文标签展示 - 每三个为一行
            if (selectedRunes.isNotEmpty()) {
                val runesList = selectedRunes.toList()
                val chunkedRunes = runesList.chunked(3)
                
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 4.dp),
                    verticalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    chunkedRunes.forEach { runesRow ->
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                            runesRow.forEach { rune ->
                        FilterChip(
                            onClick = {
                                        val newSelectedRunes = selectedRunes - rune
                                        selectedRunes = newSelectedRunes
                                        // 如果已经查询过且还有剩余符文，重新触发搜索
                                        if (hasQueriedResults && newSelectedRunes.isNotEmpty()) {
                                            viewModel.searchRecipesByMultipleRunes(newSelectedRunes.toList())
                                        }
                            },
                            label = { Text(rune, fontSize = 12.sp) },
                            selected = true,
                            trailingIcon = {
                                Icon(
                                    imageVector = Icons.Default.Close,
                                    contentDescription = "移除",
                                    modifier = Modifier.size(16.dp)
                                )
                            },
                            colors = FilterChipDefaults.filterChipColors(
                                selectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
                                selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer
                            )
                        )
                    }
                            // 填充剩余空间，使符文标签左对齐
                            repeat(3 - runesRow.size) {
                                Spacer(modifier = Modifier.weight(1f))
                            }
                        }
                    }
                }
            }

            // 下拉列表区域 - 只在展开且未查询结果时显示
            if (isDropdownExpanded && !hasQueriedResults && selectedRunes.size < 6) {
                Spacer(modifier = Modifier.height(4.dp))
                
                        // 符文分类筛选按钮行
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 4.dp),
                            horizontalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            // 金符文按钮
                            OutlinedButton(
                                onClick = {
                                    showGoldRunes = !showGoldRunes
                                    if (showGoldRunes) {
                                        showSilverRunes = false
                                        showBronzeRunes = false
                                    }
                            // 保存状态到设置
                            settingsStorage.saveRuneFilterStates(showGoldRunes, showSilverRunes, showBronzeRunes)
                                },
                                modifier = Modifier
                                    .weight(1f)
                                    .height(32.dp),
                                colors = ButtonDefaults.outlinedButtonColors(
                                    containerColor = if (showGoldRunes) MaterialTheme.colorScheme.primary else Color.White,
                                    contentColor = if (showGoldRunes) Color.White else Color.Black
                                ),
                                shape = RoundedCornerShape(6.dp),
                                border = BorderStroke(1.dp, Color.Black),
                                contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp)
                            ) {
                                Text(
                                    text = "金符文",
                                    fontSize = 10.sp,
                                    fontWeight = FontWeight.Medium
                                )
                            }

                            // 银符文按钮
                            OutlinedButton(
                                onClick = {
                                    showSilverRunes = !showSilverRunes
                                    if (showSilverRunes) {
                                        showGoldRunes = false
                                        showBronzeRunes = false
                                    }
                            // 保存状态到设置
                            settingsStorage.saveRuneFilterStates(showGoldRunes, showSilverRunes, showBronzeRunes)
                                },
                                modifier = Modifier
                                    .weight(1f)
                                    .height(32.dp),
                                colors = ButtonDefaults.outlinedButtonColors(
                                    containerColor = if (showSilverRunes) MaterialTheme.colorScheme.primary else Color.White,
                                    contentColor = if (showSilverRunes) Color.White else Color.Black
                                ),
                                shape = RoundedCornerShape(6.dp),
                                border = BorderStroke(1.dp, Color.Black),
                                contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp)
                            ) {
                                Text(
                                    text = "银符文",
                                    fontSize = 10.sp,
                                    fontWeight = FontWeight.Medium
                                )
                            }

                            // 铜符文按钮
                            OutlinedButton(
                                onClick = {
                                    showBronzeRunes = !showBronzeRunes
                                    if (showBronzeRunes) {
                                        showGoldRunes = false
                                        showSilverRunes = false
                                    }
                            // 保存状态到设置
                            settingsStorage.saveRuneFilterStates(showGoldRunes, showSilverRunes, showBronzeRunes)
                                },
                                modifier = Modifier
                                    .weight(1f)
                                    .height(32.dp),
                                colors = ButtonDefaults.outlinedButtonColors(
                                    containerColor = if (showBronzeRunes) MaterialTheme.colorScheme.primary else Color.White,
                                    contentColor = if (showBronzeRunes) Color.White else Color.Black
                                ),
                                shape = RoundedCornerShape(6.dp),
                                border = BorderStroke(1.dp, Color.Black),
                                contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp)
                            ) {
                                Text(
                                    text = "铜符文",
                                    fontSize = 10.sp,
                                    fontWeight = FontWeight.Medium
                                )
                            }
                        }
                
                Spacer(modifier = Modifier.height(8.dp))
                        
                        // 符文列表卡片
                        Card(
                            modifier = Modifier
                                .fillMaxWidth()
                                .heightIn(max = OppoCompatibilityFix.getFixedCardHeight(400.dp)),
                            elevation = CardDefaults.cardElevation(defaultElevation = 8.dp),
                            colors = OppoCompatibilityFix.getFixedCardColors()
                        ) {
                            if (filteredRunes.isNotEmpty()) {
                                LazyColumn {
                                    items(filteredRunes) { rune ->
                                        Row(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .clickable {
                                                    try {
                                                                                                if (selectedRunes.size >= 6 && rune !in selectedRunes) {
                                            // 已达到最大选择数量，不做任何操作
                                        } else {
                                                            selectedRunes = if (rune in selectedRunes) {
                                                                selectedRunes - rune
                                                            } else {
                                                                selectedRunes + rune
                                                            }
                                                            searchQuery = ""
                                                        }
                                                    } catch (e: Exception) {
                                                // 忽略符文选择错误
                                                    }
                                                }
                                                .padding(horizontal = 12.dp, vertical = 12.dp),
                                            verticalAlignment = Alignment.CenterVertically
                                        ) {
                                    // 符文名称和选中状态 - 占50%宽度
                                            Row(
                                        modifier = Modifier.weight(0.5f),
                                                verticalAlignment = Alignment.CenterVertically
                                            ) {
                                                Text(
                                                    text = rune,
                                                    fontSize = 14.sp,
                                                    color = if (rune in selectedRunes) {
                                                        MaterialTheme.colorScheme.primary
                                                    } else {
                                                        MaterialTheme.colorScheme.onSurface
                                                    },
                                                    fontWeight = if (rune in selectedRunes) {
                                                        FontWeight.Bold
                                                    } else {
                                                        FontWeight.Medium
                                                    },
                                                    modifier = Modifier.weight(1f)
                                                )
                                                if (rune in selectedRunes) {
                                                    Icon(
                                                        imageVector = Icons.Default.Check,
                                                        contentDescription = "已选择",
                                                        tint = MaterialTheme.colorScheme.primary,
                                                        modifier = Modifier.size(16.dp)
                                                    )
                                                }
                                            }
                                            
                                    // 相关菜谱数量 - 占50%宽度，左对齐
                                            val stats = runeRecipeStats[rune]
                                            val statsText = if (stats != null) {
                                                "共${stats.first}个菜谱，已有${stats.second}个"
                                            } else {
                                                "0 个菜谱"
                                            }
                                            Text(
                                                text = statsText,
                                                fontSize = 12.sp,
                                                color = MaterialTheme.colorScheme.primary,
                                                fontWeight = FontWeight.Medium,
                                                textAlign = TextAlign.Start,
                                        modifier = Modifier
                                            .weight(0.5f)
                                            .padding(start = 8.dp)
                                            )
                                        }
                                        if (rune != filteredRunes.last()) {
                                            HorizontalDivider()
                                        }
                                    }
                                }
                            } else {
                                Text(
                                    text = "未找到匹配的符文",
                                    modifier = Modifier.padding(16.dp),
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                    }
                }
            }
            
            Spacer(modifier = Modifier.height(16.dp))

            // 符文菜谱显示区域 - 只在有查询结果时显示
            if (hasQueriedResults && selectedRunes.isNotEmpty()) {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = Color(0xFFE8E8E8), // 灰色背景
                    shape = RoundedCornerShape(8.dp)
                ) {
                    Column(
                        modifier = Modifier.padding(16.dp)
                    ) {
                        // 过滤和排序菜谱，按符文分组并进行贵客冲突检测
                        val (recipesByRune, globalConflictInfo) = remember(runeRecipes, showAllRecipes, gameData, selectedRunes) {
                            val filtered = if (showAllRecipes) {
                                runeRecipes
                            } else {
                                runeRecipes.filter { it.got }
                            }
                            
                            val guests = gameData?.guests ?: emptyList()
                            
                            // 第一步：收集所有相关的菜谱和其对应的符文（跨符文）
                            val recipeToRunesMap = mutableMapOf<String, MutableSet<String>>()
                            
                            selectedRunes.forEach { runeName ->
                                guests.forEach { guest ->
                                    guest.gifts.forEach { gift ->
                                        if (gift.antique == runeName) {
                                            val recipe = filtered.find { it.name == gift.recipe }
                                            if (recipe != null) {
                                                recipeToRunesMap.getOrPut(recipe.name) { mutableSetOf() }.add(runeName)
                                            }
                                        }
                                    }
                                }
                            }
                            
                            // 第二步：全局按贵客分组（跨符文冲突检测）
                            val recipesByGuest = mutableMapOf<String, MutableList<Recipe>>()
                            
                            filtered.forEach { recipe ->
                                if (recipeToRunesMap.containsKey(recipe.name)) {
                                guests.forEach { guest ->
                                        val hasRecipeForSelectedRunes = selectedRunes.any { runeName ->
                                            guest.gifts.any { gift -> gift.recipe == recipe.name && gift.antique == runeName }
                                        }
                                        if (hasRecipeForSelectedRunes) {
                                            val guestRecipes = recipesByGuest.getOrPut(guest.name) { mutableListOf() }
                                            if (!guestRecipes.any { it.name == recipe.name }) {
                                                guestRecipes.add(recipe)
                                    }
                                }
                            }
                                }
                            }
                            
                            // 第三步：全局冲突检测（跨符文）
                            val allNoConflict = mutableListOf<Recipe>()
                            val allConflict = mutableListOf<Recipe>()
                            
                            recipesByGuest.forEach { (guestName, recipes) ->
                                System.out.println("贵客冲突检测 - 贵客: $guestName, 菜谱数量: ${recipes.size}")
                                
                                if (recipes.size == 1) {
                                    // 只有一个菜谱，无冲突
                                    allNoConflict.addAll(recipes)
                                    System.out.println("  单个菜谱，无冲突: ${recipes.map { it.name }}")
                                } else {
                                    // 多个菜谱有冲突，需要选择一个作为无冲突
                                    // 双贵客菜谱时间除以2后再判断
                                    System.out.println("  多个菜谱有冲突，开始时间调整计算:")
                                    
                                    // 先收集所有菜谱的贵客数量信息
                                    val recipeGuestCountMap = mutableMapOf<String, Int>()
                                    recipes.forEach { recipe ->
                                        val guestCount = gameData?.guests?.count { guest ->
                                            guest.gifts.any { gift -> 
                                                gift.recipe == recipe.name 
                                            }
                                        } ?: 1
                                        recipeGuestCountMap[recipe.name] = guestCount
                                    }
                                    
                                    val recipesWithAdjustedTime = recipes.map { recipe ->
                                        val guestCount = recipeGuestCountMap[recipe.name] ?: 1
                                        val adjustedTime = if (guestCount >= 2) {
                                            recipe.time / 2.0
                                        } else {
                                            recipe.time.toDouble()
                                        }
                                        Triple(recipe, adjustedTime, guestCount)
                                    }
                                    
                                    // 输出每个菜谱的详细信息
                                    recipesWithAdjustedTime.forEach { (recipe, adjustedTime, guestCount) ->
                                        val timeDetail = if (guestCount >= 2) {
                                            "${recipe.name}: ${recipe.time}秒/2 = ${adjustedTime.toInt()}秒 (${guestCount}贵客)"
                                        } else {
                                            "${recipe.name}: ${recipe.time}秒 (${guestCount}贵客)"
                                        }
                                        System.out.println("    $timeDetail")
                                    }
                                    
                                    // 按调整后的时间排序
                                    val sortedByAdjustedTime = recipesWithAdjustedTime.sortedBy { it.second }
                                    
                                    // 选择调整后时间最短的作为无冲突菜谱
                                    val selectedRecipeInfo = sortedByAdjustedTime.first()
                                    val selectedRecipe = selectedRecipeInfo.first
                                    val selectedAdjustedTime = selectedRecipeInfo.second
                                    val selectedGuestCount = selectedRecipeInfo.third
                                    
                                    allNoConflict.add(selectedRecipe)
                                    
                                    // 其余菜谱都是冲突菜谱
                                    val remainingRecipes = sortedByAdjustedTime.drop(1).map { it.first }
                                    allConflict.addAll(remainingRecipes)
                                    
                                    // 输出调试信息
                                    val timeInfo = if (selectedGuestCount >= 2) {
                                        "多贵客菜谱(时间${selectedRecipe.time}秒/2=${selectedAdjustedTime.toInt()}秒)"
                                    } else {
                                        "单贵客菜谱(时间${selectedRecipe.time}秒)"
                                    }
                                    System.out.println("  选择 ${selectedRecipe.name} 作为无冲突菜谱 ($timeInfo)")
                                    System.out.println("  冲突菜谱: ${remainingRecipes.map { it.name }}")
                                }
                            }
                            
                            // 第四步：按符文重新分组结果
                            val result = mutableMapOf<String, Pair<List<Recipe>, List<Recipe>>>()
                            val sortComparator = compareByDescending<Recipe> { it.got }.thenBy { it.time }
                            
                            selectedRunes.forEach { runeName ->
                                val runeNoConflict = allNoConflict.filter { recipe ->
                                    recipeToRunesMap[recipe.name]?.contains(runeName) == true
                                }.distinctBy { it.name }  // 按菜谱名称去重
                                
                                val runeConflict = allConflict.filter { recipe ->
                                    recipeToRunesMap[recipe.name]?.contains(runeName) == true
                                }.distinctBy { it.name }  // 按菜谱名称去重
                                
                                result[runeName] = Pair(
                                    runeNoConflict.sortedWith(sortComparator),
                                    runeConflict.sortedWith(sortComparator)
                            )
                            }
                            
                            // 返回符文分组结果和全局冲突信息
                            Pair(result, Pair(allNoConflict, allConflict))
                        }
                        
                        val totalRecipeCount = recipesByRune.values.sumOf { (noConflict, conflict) -> 
                            noConflict.size + conflict.size 
                        }
                        
                        // 标题和查询全部按钮
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(bottom = 8.dp),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(
                                text = "以上符文菜谱总数 (${totalRecipeCount})",
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Medium,
                                modifier = Modifier.weight(1f)
                            )
                            
                            // 查询全部/只看已有 切换按钮
                            OutlinedButton(
                                onClick = { showAllRecipes = !showAllRecipes },
                                modifier = Modifier.height(32.dp),
                                colors = ButtonDefaults.outlinedButtonColors(
                                    containerColor = if (showAllRecipes) MaterialTheme.colorScheme.primary else Color.White,
                                    contentColor = if (showAllRecipes) Color.White else Color.Black
                                ),
                                shape = RoundedCornerShape(6.dp),
                                border = BorderStroke(1.dp, Color.Black),
                                contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp)
                            ) {
                                Text(
                                    text = if (showAllRecipes) "只看已有" else "查询全部",
                                    fontSize = 10.sp,
                                    fontWeight = FontWeight.Medium
                                )
                            }
                        }
                        
                        // 菜谱列表或加载状态
                        if (isLoadingRuneRecipes) {
                            Box(
                                modifier = Modifier.fillMaxSize(),
                                contentAlignment = Alignment.Center
                            ) {
                                CircularProgressIndicator()
                            }
                        } else if (totalRecipeCount == 0) {
                            Box(
                                modifier = Modifier.fillMaxSize(),
                                contentAlignment = Alignment.Center
                            ) {
                                Column(
                                    horizontalAlignment = Alignment.CenterHorizontally,
                                    verticalArrangement = Arrangement.spacedBy(8.dp)
                                ) {
                                    Icon(
                                        imageVector = Icons.Default.Search,
                                        contentDescription = null,
                                        tint = MaterialTheme.colorScheme.onSurfaceVariant,
                                        modifier = Modifier.size(48.dp)
                                    )
                                    Text(
                                        text = if (showAllRecipes) "未找到相关菜谱" else "暂无已拥有的菜谱",
                                        fontSize = 16.sp,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                            }
                        } else {
                            // 计算总的无冲突和有冲突菜谱数量
                            val totalNoConflictCount = recipesByRune.values.sumOf { it.first.size }
                            val totalConflictCount = recipesByRune.values.sumOf { it.second.size }
                            
                            // 标签页布局
                            Column(
                                modifier = Modifier.fillMaxWidth()
                            ) {
                                // 自定义标签页头部 - 胶囊样式
                                Card(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(horizontal = 16.dp),
                                        shape = RoundedCornerShape(20.dp),
                                        colors = CardDefaults.cardColors(
                                            containerColor = Color(0xFFE3F2FD)
                                        ),
                                        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
                                    ) {
                                        Row(
                                            modifier = Modifier.padding(4.dp)
                                        ) {
                                            // 无冲突标签
                                            Surface(
                                                onClick = { selectedTabIndex = 0 },
                                                modifier = Modifier
                                                    .weight(1f)
                                                    .height(28.dp),
                                                shape = RoundedCornerShape(16.dp),
                                                color = if (selectedTabIndex == 0) {
                                                    MaterialTheme.colorScheme.primary
                                                } else {
                                                    Color.Transparent
                                                }
                                            ) {
                                                Box(
                                                    modifier = Modifier.fillMaxSize(),
                                                    contentAlignment = Alignment.Center
                                                ) {
                                                    Text(
                                                        text = "无冲突 ($totalNoConflictCount)",
                                                        fontSize = 12.sp,
                                                        fontWeight = FontWeight.Medium,
                                                        color = if (selectedTabIndex == 0) {
                                                            Color.White
                                                        } else {
                                                            MaterialTheme.colorScheme.primary
                                                        }
                                                    )
                                                }
                                            }
                                            
                                            Spacer(modifier = Modifier.width(4.dp))
                                            
                                            // 有冲突标签
                                            Surface(
                                                onClick = { selectedTabIndex = 1 },
                                                modifier = Modifier
                                                    .weight(1f)
                                                    .height(28.dp),
                                                shape = RoundedCornerShape(16.dp),
                                                color = if (selectedTabIndex == 1) {
                                                    MaterialTheme.colorScheme.primary
                                                } else {
                                                    Color.Transparent
                                                }
                                            ) {
                                                Box(
                                                    modifier = Modifier.fillMaxSize(),
                                                    contentAlignment = Alignment.Center
                                                ) {
                                                    Text(
                                                        text = "有冲突 ($totalConflictCount)",
                                                        fontSize = 12.sp,
                                                        fontWeight = FontWeight.Medium,
                                                        color = if (selectedTabIndex == 1) {
                                                            Color.White
                                                        } else {
                                                            MaterialTheme.colorScheme.primary
                                                        }
                                                    )
                                                }
                                            }
                                        }
                                    }
                                
                                Spacer(modifier = Modifier.height(16.dp))
                                
                                // 标签页内容
                                when (selectedTabIndex) {
                                    0 -> {
                                        // 无冲突贵客菜谱内容
                                        if (totalNoConflictCount > 0) {
                            Column(
                                modifier = Modifier.fillMaxWidth(),
                                                verticalArrangement = Arrangement.spacedBy(12.dp)
                            ) {
                                                selectedRunes.forEach { runeName ->
                                                    val (noConflictRecipes, _) = recipesByRune[runeName] ?: Pair(emptyList(), emptyList())
                                                    
                                if (noConflictRecipes.isNotEmpty()) {
                                                        // 符文子标题行：符文名称 + 收起展开按钮
                                    Row(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(start = 16.dp, top = 4.dp, bottom = 4.dp),
                                        verticalAlignment = Alignment.CenterVertically,
                                        horizontalArrangement = Arrangement.SpaceBetween
                                    ) {
                                    Text(
                                                            text = "$runeName (${noConflictRecipes.size})",
                                                            fontSize = 16.sp,
                                                            fontWeight = FontWeight.Bold,
                                            color = MaterialTheme.colorScheme.primary
                                        )
                                        
                                        // 收起展开按钮
                                        IconButton(
                                            onClick = {
                                                collapsedRunes = if (runeName in collapsedRunes) {
                                                    collapsedRunes - runeName
                                                } else {
                                                    collapsedRunes + runeName
                                                }
                                            },
                                            modifier = Modifier.size(24.dp)
                                        ) {
                                            Icon(
                                                imageVector = if (runeName in collapsedRunes) Icons.Default.KeyboardArrowDown else Icons.Default.KeyboardArrowUp,
                                                contentDescription = if (runeName in collapsedRunes) "展开" else "收起",
                                                tint = MaterialTheme.colorScheme.primary,
                                                modifier = Modifier.size(20.dp)
                                            )
                                        }
                                    }
                                    
                                                        // 该符文的无冲突菜谱（根据折叠状态显示）
                                                        if (runeName !in collapsedRunes) {
                                    Column(
                                        modifier = Modifier.fillMaxWidth(),
                                        verticalArrangement = Arrangement.spacedBy(4.dp)
                                    ) {
                                        noConflictRecipes.forEach { recipe ->
                                            RuneRecipeItem(
                                                recipe = recipe,
                                                guests = gameData?.guests ?: emptyList(),
                                                                    modifier = Modifier.fillMaxWidth(),
                                                                    isConflictTab = false,
                                                                    recipesByRune = recipesByRune,
                                                                    selectedRunes = selectedRunes,
                                                                    globalConflictInfo = globalConflictInfo,
                                                                    onShowConflict = { selectedRecipe ->
                                                                        conflictDialogRecipe = selectedRecipe
                                                                        showConflictDialog = true
                                                                    }
                                                                )
                                                            }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        } else {
                                            Box(
                                                modifier = Modifier.fillMaxWidth().padding(32.dp),
                                                contentAlignment = Alignment.Center
                                            ) {
                                                Text(
                                                    text = "暂无无冲突菜谱",
                                                    fontSize = 16.sp,
                                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                                )
                                            }
                                        }
                                    }
                                    1 -> {
                                        // 有冲突贵客菜谱内容
                                        if (totalConflictCount > 0) {
                                            Column(
                                                modifier = Modifier.fillMaxWidth(),
                                                verticalArrangement = Arrangement.spacedBy(12.dp)
                                            ) {
                                                selectedRunes.forEach { runeName ->
                                                    val (_, conflictRecipes) = recipesByRune[runeName] ?: Pair(emptyList(), emptyList())
                                                    
                                                    if (conflictRecipes.isNotEmpty()) {
                                                        // 符文子标题行：符文名称 + 收起展开按钮
                                    Row(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(start = 16.dp, top = 4.dp, bottom = 4.dp),
                                        verticalAlignment = Alignment.CenterVertically,
                                        horizontalArrangement = Arrangement.SpaceBetween
                                    ) {
                                    Text(
                                                            text = "$runeName (${conflictRecipes.size})",
                                                            fontSize = 16.sp,
                                                            fontWeight = FontWeight.Bold,
                                            color = MaterialTheme.colorScheme.error
                                        )
                                        
                                        // 收起展开按钮
                                        IconButton(
                                            onClick = {
                                                collapsedRunes = if (runeName in collapsedRunes) {
                                                    collapsedRunes - runeName
                                                } else {
                                                    collapsedRunes + runeName
                                                }
                                            },
                                            modifier = Modifier.size(24.dp)
                                        ) {
                                            Icon(
                                                imageVector = if (runeName in collapsedRunes) Icons.Default.KeyboardArrowDown else Icons.Default.KeyboardArrowUp,
                                                contentDescription = if (runeName in collapsedRunes) "展开" else "收起",
                                                tint = MaterialTheme.colorScheme.error,
                                                modifier = Modifier.size(20.dp)
                                            )
                                        }
                                    }
                                    
                                                        // 该符文的有冲突菜谱（根据折叠状态显示）
                                                        if (runeName !in collapsedRunes) {
                                    Column(
                                        modifier = Modifier.fillMaxWidth(),
                                        verticalArrangement = Arrangement.spacedBy(4.dp)
                                    ) {
                                        conflictRecipes.forEach { recipe ->
                                            RuneRecipeItem(
                                                recipe = recipe,
                                                guests = gameData?.guests ?: emptyList(),
                                                                    modifier = Modifier.fillMaxWidth(),
                                                                    isConflictTab = true
                                            )
                                        }
                                        }
                                    }
                                }
                            }
                        }
                                        } else {
                                            Box(
                                                modifier = Modifier.fillMaxWidth().padding(32.dp),
                                                contentAlignment = Alignment.Center
                                            ) {
                                                Text(
                                                    text = "暂无冲突菜谱",
                                                    fontSize = 16.sp,
                                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                                )
                }
                                        }
                                    }
                                }
                            }
                        }
                        
                        // 冲突菜谱弹窗
                        if (showConflictDialog && conflictDialogRecipe != null) {
                            ConflictRecipeDialog(
                                recipe = conflictDialogRecipe!!,
                                recipesByRune = recipesByRune,
                                selectedRunes = selectedRunes,
                                guests = gameData?.guests ?: emptyList(),
                                globalConflictInfo = globalConflictInfo,
                                onDismiss = { 
                                    showConflictDialog = false
                                    conflictDialogRecipe = null
                                }
                            )
                        }
                        

                        

                    }
                }
            } else if (!hasQueriedResults) {
                // 未查询时的空白区域
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = Color(0xFFE8E8E8), // 灰色背景
                    shape = RoundedCornerShape(8.dp)
                 ) {
                     Box(
                        modifier = Modifier.fillMaxSize(),
                        contentAlignment = Alignment.Center
                     ) {
                        // 当选择满6个符文时显示提示信息
                        if (selectedRunes.size >= 6) {
                            Column(
                                modifier = Modifier.padding(16.dp),
                                horizontalAlignment = Alignment.CenterHorizontally,
                                verticalArrangement = Arrangement.spacedBy(8.dp)
                            ) {
                                Icon(
                                    imageVector = Icons.Default.Info,
                                    contentDescription = "提示",
                                    modifier = Modifier.size(48.dp),
                                    tint = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                                Text(
                                    text = "一次最多查询6种符文冲突",
                                    fontSize = 16.sp,
                                    fontWeight = FontWeight.Medium,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                                    textAlign = TextAlign.Center
                                )
                     }
                 }
             }
        }
    }
                }
                1 -> {
                    // 贵客率计算器页面
                    Column(
                        modifier = Modifier.fillMaxWidth(),
                        verticalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        // 计算结果显示区域
                        var isResultExpanded by remember { mutableStateOf(false) }
                        
                        // 份数输入框的焦点状态管理
                        var isFocused by remember { mutableStateOf(false) }
                        val focusRequester = remember { FocusRequester() }
                        
                        // 光标自动隐藏计时器
                        var cursorVisible by remember { mutableStateOf(false) }
                        var lastInputTime by remember { mutableStateOf(0L) }
                        var inputFieldEnabled by remember { mutableStateOf(true) }
                        
                        // 2秒后自动隐藏光标
                        LaunchedEffect(lastInputTime) {
                            if (lastInputTime > 0) {
                                delay(2000) // 2秒延迟
                                cursorVisible = false
                                // 失去焦点以隐藏选择指示器
                                focusRequester.freeFocus()
                                // 暂时禁用输入框来清除选择状态
                                inputFieldEnabled = false
                                delay(50) // 短暂延迟
                                inputFieldEnabled = true
                            }
                        }
                        
                        Card(
                            modifier = Modifier.fillMaxWidth(),
                            colors = CardDefaults.cardColors(
                                containerColor = MaterialTheme.colorScheme.surface
                            ),
                            border = BorderStroke(
                                width = 1.dp,
                                color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f)
                            ),
                            elevation = CardDefaults.cardElevation(defaultElevation = 0.dp)
                        ) {
                            Column(
                                modifier = Modifier.padding(8.dp)
                            ) {
                                // 标题行：计算结果居中 + 展开收起按钮（只有这里可以点击）
                                Box(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .clickable(
                                            interactionSource = remember { MutableInteractionSource() },
                                            indication = null
                                        ) { isResultExpanded = !isResultExpanded },
                                    contentAlignment = Alignment.Center
                                ) {
                                    Text(
                                        text = "计算结果",
                                        fontSize = 14.sp,
                                        fontWeight = FontWeight.Medium,
                                        color = MaterialTheme.colorScheme.primary
                                    )
                                    
                                    // 右侧箭头图标
                                    Icon(
                                        imageVector = if (isResultExpanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
                                        contentDescription = if (isResultExpanded) "收起" else "展开",
                                        tint = MaterialTheme.colorScheme.onSurfaceVariant,
                                        modifier = Modifier
                                            .size(20.dp)
                                            .align(Alignment.CenterEnd)
                                    )
                                }
                                
                                // 展开的内容
                                if (isResultExpanded) {
                                    Column(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(top = 8.dp),
                                        verticalArrangement = Arrangement.spacedBy(2.dp)
                                    ) {
                                        // 计算贵客率和时间总和
                                        val currentPersonalData = viewModel.personalData.collectAsState().value
                                        val totalGuestRate = remember(calculatorSelectedChefs, calculatorSelectedEquips, calculatorSelectedLevels, calculatorSelectedAmbers, calculatorSelectedPortions, gameData, currentPersonalData, currentDefaultAllUltimate) {
                                            var sum = 0.0
                                            calculatorSelectedChefs.forEachIndexed { index, chef ->
                                                if (chef.name.isNotEmpty()) {
                                                    val selectedLevel = calculatorSelectedLevels.getOrNull(index)
                                                    val selectedAmbers = calculatorSelectedAmbers.getOrNull(index)
                                                    val selectedEquip = calculatorSelectedEquips.getOrNull(index)
                                                    val guestRate = calculateTotalGuestRateBonusWithCalculatorData(chef, gameData?.skills ?: emptyList(), gameData, currentPersonalData, selectedLevel, selectedAmbers, selectedEquip, currentDefaultAllUltimate)
                                                    sum += guestRate
                                                }
                                            }
                                            
                                                    // 计算场上性别技能提供的额外加成
        val fieldGenderBonus = calculateFieldGenderSkillBonus(calculatorSelectedChefs, gameData?.skills ?: emptyList(), currentDefaultAllUltimate)
                                            sum += fieldGenderBonus
                                            
                                            sum
                                        }
                                        
                                        val totalCritRate = remember(calculatorSelectedChefs, calculatorSelectedEquips, calculatorSelectedLevels, calculatorSelectedAmbers, calculatorSelectedPortions, gameData, currentPersonalData, currentDefaultAllUltimate) {
                                            var sum = 100.0 // 默认从100开始
                                            calculatorSelectedChefs.forEachIndexed { index, chef ->
                                                if (chef.name.isNotEmpty()) {
                                                    // 使用计算器中选择的厨具，而不是个人数据中的厨具
                                                    val equip = calculatorSelectedEquips.getOrNull(index)
                                                    val critRate = if (equip != null && equip.name.isNotEmpty()) {
                                                        // 使用计算器中选择的厨具计算暴击率
                                                        var totalCritRate = 100.0 // 默认从100开始
                                                        
                                                        // 1. 计算基础技能暴击率
                                                        if (chef.skill > 0) {
                                                            val baseSkill = gameData?.skills?.find { it.skillId == chef.skill }
                                                            if (baseSkill != null) {
                                                                totalCritRate += extractCritRateFromSkillForCalculator(baseSkill.desc)
                                                            }
                                                        }
                                                        
                                                        // 2. 计算修炼技能暴击率
                                                        val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(chef, gameData?.skills ?: emptyList(), currentDefaultAllUltimate)
                                                        totalCritRate += extractCritRateFromSkillForCalculator(ultimateSkillDesc)
                                                        
                                                        // 3. 计算计算器中选择的厨具暴击率
                                                        // 检查厨师是否有厨具技能效果翻倍技能
                                                        val hasEquipSkillMultiplier = hasEquipSkillMultiplier(chef, gameData?.skills ?: emptyList())
                                                        val multiplier = if (hasEquipSkillMultiplier) 2.0 else 1.0
                                                        
                                                        for (skillId in equip.skill) {
                                                            val skill = gameData?.skills?.find { it.skillId == skillId }
                                                            if (skill != null) {
                                                                totalCritRate += extractCritRateFromSkillForCalculator(skill.desc) * multiplier
                                                            }
                                                        }
                                                        
                                                        totalCritRate
                                                    } else {
                                                        // 当计算器中未选择厨具时，只计算厨师技能暴击率，不包含厨具暴击率
                                                        var totalCritRate = 100.0 // 默认从100开始
                                                        
                                                        // 1. 计算基础技能暴击率
                                                        if (chef.skill > 0) {
                                                            val baseSkill = gameData?.skills?.find { it.skillId == chef.skill }
                                                            if (baseSkill != null) {
                                                                totalCritRate += extractCritRateFromSkillForCalculator(baseSkill.desc)
                                                            }
                                                        }
                                                        
                                                        // 2. 计算修炼技能暴击率
                                                        val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(chef, gameData?.skills ?: emptyList(), currentDefaultAllUltimate)
                                                        totalCritRate += extractCritRateFromSkillForCalculator(ultimateSkillDesc)
                                                        
                                                        // 注意：这里不再调用 calculateTotalCritRateForCalculator，因为该函数会包含个人数据中的厨具
                                                        
                                                        totalCritRate
                                                    }
                                                    sum += critRate - 100.0 // 减去100，因为我们已经包含了100的基础值
                                                }
                                            }
                                            sum
                                        }
                                        
                                        val totalTimeBonus = remember(calculatorSelectedChefs, calculatorSelectedEquips, calculatorSelectedPortions, gameData, currentPersonalData, currentDefaultAllUltimate) {
                                            var sum = 0.0
                                            calculatorSelectedChefs.forEachIndexed { index, chef ->
                                                if (chef.name.isNotEmpty()) {
                                                    val equip = calculatorSelectedEquips.getOrNull(index)
                                                    val timeBonus = calculateOpeningTimeBonus(chef, equip, gameData?.skills ?: emptyList(), gameData, currentPersonalData, currentDefaultAllUltimate)
                                                    sum += timeBonus
                                                }
                                            }
                                            sum
                                        }
                                        
                                        // 注意：totalTimeBonus中，正值表示增加时间，负值表示减少时间
                                        // 所以最终时间应该是：100 + totalTimeBonus
                                        val finalTimeRate = 100.0 + totalTimeBonus
                                        
                                        // 计算实际贵客率
                                        val actualGuestRate = remember(calculatorSelectedStarLevel, calculatorSelectedPortions, totalGuestRate) {
                                            calculateActualGuestRate(calculatorSelectedStarLevel, calculatorSelectedPortions, totalGuestRate)
                                        }
                                        
                                        // 计算符文率
                                        val runeRate = remember(calculatorSelectedRank, calculatorSelectedChefs, gameData?.skills, settingsStorage.getCalculatorDefaultAllUltimate()) {
                                            getRuneRateByRankWithOverride(calculatorSelectedRank, calculatorSelectedChefs, gameData?.skills ?: emptyList(), settingsStorage.getCalculatorDefaultAllUltimate())
                                        }
                                        
                                        // 计算衍生数据（按照计算顺序和空值判断）
                                        val hundredPotOutput = remember(actualGuestRate, runeRate, totalCritRate) {
                                            calculateHundredPotOutput(actualGuestRate, runeRate, totalCritRate)
                                        }
                                        val unitFood = remember(actualGuestRate, runeRate, totalCritRate, calculatorSelectedPortions) {
                                            calculateUnitFood(actualGuestRate, runeRate, totalCritRate, calculatorSelectedPortions)
                                        }
                                        val unitTime = remember(unitFood, finalTimeRate) {
                                            calculateUnitTime(unitFood, finalTimeRate)
                                        }
                                        
                                        // 第一行：贵客率、暴击、时间
                                        Row(
                                            modifier = Modifier.fillMaxWidth(),
                                            horizontalArrangement = Arrangement.SpaceBetween
                                        ) {
                                            Text(
                                                text = "贵客率:${formatNumber(totalGuestRate, 1)}%",
                                                fontSize = 10.sp,
                                                fontWeight = FontWeight.Medium,
                                                color = MaterialTheme.colorScheme.onSurface,
                                                modifier = Modifier.weight(1f),
                                                textAlign = TextAlign.Start
                                            )
                                            Text(
                                                text = "总暴击率:${formatNumber(totalCritRate, 1)}%",
                                                fontSize = 10.sp,
                                                fontWeight = FontWeight.Medium,
                                                color = MaterialTheme.colorScheme.onSurface,
                                                modifier = Modifier
                                                    .weight(1f)
                                                    .padding(start = 16.dp),
                                                textAlign = TextAlign.Start
                                            )
                                            Text(
                                                text = "时间:${formatNumber(finalTimeRate, 1)}%",
                                                fontSize = 10.sp,
                                                fontWeight = FontWeight.Medium,
                                                color = MaterialTheme.colorScheme.onSurface,
                                                modifier = Modifier
                                                    .weight(1f)
                                                    .padding(start = 20.dp),
                                                textAlign = TextAlign.Start
                                            )
                                        }
                                        
                                        // 第二行：实际贵客率、符文率、百锅产出
                                        Row(
                                            modifier = Modifier.fillMaxWidth(),
                                            horizontalArrangement = Arrangement.SpaceBetween
                                        ) {
                                            Text(
                                                text = "实际贵客率: ${formatNumber(actualGuestRate, 2)}%",
                                                fontSize = 10.sp,
                                                fontWeight = FontWeight.Medium,
                                                color = MaterialTheme.colorScheme.onSurface,
                                                modifier = Modifier.weight(1f),
                                                textAlign = TextAlign.Start
                                            )
                                            Text(
                                                text = "符文率: ${runeRate}%",
                                                fontSize = 10.sp,
                                                fontWeight = FontWeight.Medium,
                                                color = MaterialTheme.colorScheme.onSurface,
                                                modifier = Modifier
                                                    .weight(1f)
                                                    .padding(start = 16.dp),
                                                textAlign = TextAlign.Start
                                            )
                                            Text(
                                                text = "百锅产出: ${formatNumber(hundredPotOutput, 2)}",
                                                fontSize = 10.sp,
                                                fontWeight = FontWeight.Medium,
                                                color = MaterialTheme.colorScheme.onSurface,
                                                modifier = Modifier
                                                    .weight(1f)
                                                    .padding(start = 20.dp),
                                                textAlign = TextAlign.Start
                                            )
                                        }
                                        
                                        // 第三行：星级、品级、份数
                                        Row(
                                            modifier = Modifier.fillMaxWidth(),
                                            horizontalArrangement = Arrangement.SpaceBetween,
                                            verticalAlignment = Alignment.CenterVertically
                                        ) {
                                            // 第一列：星级
                                            Row(
                                                modifier = Modifier.weight(1f),
                                                verticalAlignment = Alignment.CenterVertically,
                                                horizontalArrangement = Arrangement.spacedBy(8.dp)
                                            ) {
                                                Text(
                                                    text = "星级",
                                                    fontSize = 10.sp,
                                                    color = Color.Black
                                                )
                                                CalculatorStarLevelDropdown(
                                                    selectedStarLevel = calculatorSelectedStarLevel,
                                                    onStarLevelSelected = { starLevel ->
                                                        calculatorSelectedStarLevel = starLevel
                                                    },
                                                    modifier = Modifier
                                                        .width(50.dp)
                                                        .height(20.dp)
                                                )
                                            }
                                            
                                            // 第二列：品级
                                            Row(
                                                modifier = Modifier.weight(1f),
                                                verticalAlignment = Alignment.CenterVertically,
                                                horizontalArrangement = Arrangement.spacedBy(8.dp)
                                            ) {
                                                Text(
                                                    text = "品级",
                                                    fontSize = 10.sp,
                                                    color = Color.Black
                                                )
                                                CalculatorRankDropdown(
                                                    selectedRank = calculatorSelectedRank,
                                                    onRankSelected = { rank ->
                                                        calculatorSelectedRank = rank
                                                    },
                                                    modifier = Modifier
                                                        .width(50.dp)
                                                        .height(20.dp)
                                                )
                                            }
                                            
                                            // 第三列：份数
                                            Row(
                                                modifier = Modifier.weight(1f),
                                                verticalAlignment = Alignment.CenterVertically,
                                                horizontalArrangement = Arrangement.spacedBy(8.dp)
                                            ) {
                                                Text(
                                                    text = "份数",
                                                    fontSize = 10.sp,
                                                    color = Color.Black
                                                )
                                                // 份数输入框的文本状态
                                                var inputText by remember { mutableStateOf(calculatorSelectedPortions.toString()) }
                                                
                                                Row(
                                                    horizontalArrangement = Arrangement.spacedBy(4.dp)
                                                ) {
                                                    // 减号按钮（长方形）
                                                    OutlinedCard(
                                                        modifier = Modifier
                                                            .width(16.dp)
                                                            .height(20.dp),
                                                        border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
                                                        shape = RoundedCornerShape(4.dp)
                                                    ) {
                                                        Box(
                                                            modifier = Modifier
                                                                .fillMaxSize()
                                                                .clickable {
                                                                    if (calculatorSelectedPortions > 0) {
                                                                        calculatorSelectedPortions--
                                                                        inputText = calculatorSelectedPortions.toString()
                                                                        isPortionsManuallyModified = true // 标记为手动修改
                                                                        // 更新光标显示时间
                                                                        lastInputTime = System.currentTimeMillis()
                                                                        cursorVisible = true
                                                                        
                                                                        // 同步更新所有已选择菜谱的槽位份数
                                                                        updateRecipePortionsForAllSelectedRecipes()
                                                                    }
                                                                },
                                                            contentAlignment = Alignment.Center
                                                        ) {
                                                            Text(
                                                                text = "-",
                                                                fontSize = 10.sp,
                                                                color = MaterialTheme.colorScheme.onSurface,
                                                                textAlign = TextAlign.Center,
                                                                lineHeight = 20.sp
                                                            )
                                                        }
                                                    }
                                                    
                                                    // 中间的数字输入框（长方形，可输入）
                                                    Box(
                                                        modifier = Modifier
                                                            .width(32.dp)
                                                            .height(20.dp)
                                                            .border(
                                                                width = 1.dp,
                                                                color = MaterialTheme.colorScheme.outline,
                                                                shape = RoundedCornerShape(2.dp)
                                                            )
                                                            .background(
                                                                color = MaterialTheme.colorScheme.surface,
                                                                shape = RoundedCornerShape(2.dp)
                                                            )
                                                            .clickable(
                                                                interactionSource = remember { MutableInteractionSource() },
                                                                indication = null
                                                            ) {
                                                                // 点击输入框时聚焦
                                                                focusRequester.requestFocus()
                                                            },
                                                        contentAlignment = Alignment.Center
                                                    ) {
                                                        BasicTextField(
                                                            value = inputText,
                                                            enabled = inputFieldEnabled,
                                                            onValueChange = { newValue ->
                                                                val filteredValue = newValue.filter { it.isDigit() }
                                                                inputText = filteredValue
                                                                
                                                                // 更新最后输入时间，显示光标
                                                                lastInputTime = System.currentTimeMillis()
                                                                cursorVisible = true
                                                                
                                                                if (filteredValue.isNotEmpty()) {
                                                                    val intValue = filteredValue.toIntOrNull()
                                                                    if (intValue != null) {
                                                                        // 限制最大值为99
                                                                        if (intValue > 99) {
                                                                            calculatorSelectedPortions = 99
                                                                            inputText = "99"
                                                                        } else {
                                                                            calculatorSelectedPortions = intValue
                                                                        }
                                                                        isPortionsManuallyModified = true // 标记为手动修改
                                                                        
                                                                        // 同步更新所有已选择菜谱的槽位份数
                                                                        updateRecipePortionsForAllSelectedRecipes()
                                                                    }
                                                                } else {
                                                                    // 如果输入为空，不更新calculatorQuantity，保持原值
                                                                }
                                                            },
                                                            textStyle = androidx.compose.ui.text.TextStyle(
                                                                fontSize = 10.sp,
                                                                fontWeight = FontWeight.Medium,
                                                                color = MaterialTheme.colorScheme.onSurface,
                                                                textAlign = TextAlign.Center,
                                                                lineHeight = 10.sp
                                                            ),
                                                            singleLine = true,
                                                            modifier = Modifier
                                                                .fillMaxSize()
                                                                .focusRequester(focusRequester)
                                                                .onFocusChanged { focusState ->
                                                                    isFocused = focusState.isFocused
                                                                    // 获得焦点时显示光标
                                                                    if (focusState.isFocused) {
                                                                        cursorVisible = true
                                                                        lastInputTime = System.currentTimeMillis()
                                                                    }
                                                                    // 失去焦点时处理输入值
                                                                    if (!focusState.isFocused) {
                                                                        if (inputText.isEmpty() || inputText.toIntOrNull() == null) {
                                                                            // 如果输入为空或无效，重置为当前值
                                                                            inputText = calculatorSelectedPortions.toString()
                                                                        } else {
                                                                            val intValue = inputText.toIntOrNull() ?: 0
                                                                            if (intValue > 99) {
                                                                                calculatorSelectedPortions = 99
                                                                                inputText = "99"
                                                                            } else if (intValue < 0) {
                                                                                calculatorSelectedPortions = 0
                                                                                inputText = "0"
                                                                            } else {
                                                                                // 确保calculatorSelectedPortions与inputText同步
                                                                                calculatorSelectedPortions = intValue
                                                                                
                                                                                // 同步更新所有已选择菜谱的槽位份数
                                                                                updateRecipePortionsForAllSelectedRecipes()
                                                                            }
                                                                        }
                                                                    }
                                                                },
                                                            cursorBrush = if (cursorVisible) SolidColor(MaterialTheme.colorScheme.primary) else SolidColor(Color.Transparent)
                                                        ) { innerTextField ->
                                                            Box(
                                                                modifier = Modifier.fillMaxSize(),
                                                                contentAlignment = Alignment.Center
                                                            ) {
                                                                innerTextField()
                                                            }
                                                        }
                                                    }
                                                    
                                                    // 同步inputText和calculatorSelectedPortions，并更新所有已选择菜谱的份数
                                                    LaunchedEffect(calculatorSelectedPortions) {
                                                        if (inputText != calculatorSelectedPortions.toString()) {
                                                            inputText = calculatorSelectedPortions.toString()
                                                        }
                                                        
                                                        // 当计算结果中的份数变化时，同步更新所有已选择菜谱的槽位份数
                                                        val updatedPortions = calculatorRecipePortions.toMutableList()
                                                        var hasChanges = false
                                                        
                                                        for (i in 0 until 9) {
                                                            val recipe = calculatorSelectedRecipes.getOrNull(i)
                                                            if (recipe != null && recipe.name.isNotEmpty()) {
                                                                // 检查该菜谱是否为强补菜谱
                                                                val isSupplementedRecipe = recipe.rarity in 1..2 && 
                                                                    recipe.time <= 300 // 5分钟以内的菜谱
                                                                
                                                                // 如果是强补菜谱，份数保持为1，不参与同步更新
                                                                if (isSupplementedRecipe) {
                                                                    System.out.println("槽位$i 菜谱 ${recipe.name} 是强补菜谱，份数保持为1")
                                                                    continue
                                                                }
                                                                
                                                                // 如果该槽位有菜谱，更新份数
                                                                if (updatedPortions[i] != calculatorSelectedPortions) {
                                                                    updatedPortions[i] = calculatorSelectedPortions
                                                                    hasChanges = true
                                                                }
                                                            }
                                                        }
                                                        
                                                        if (hasChanges) {
                                                            calculatorRecipePortions = updatedPortions
                                                            System.out.println("份数变化同步更新菜谱槽位份数: ${updatedPortions}")
                                                        }
                                                    }
                                                    
                                                    // 加号按钮（长方形）
                                                    OutlinedCard(
                                                        modifier = Modifier
                                                            .width(16.dp)
                                                            .height(20.dp),
                                                        border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
                                                        shape = RoundedCornerShape(4.dp)
                                                    ) {
                                                        Box(
                                                            modifier = Modifier
                                                                .fillMaxSize()
                                                                .clickable {
                                                                    if (calculatorSelectedPortions < 99) {
                                                                        calculatorSelectedPortions++
                                                                        inputText = calculatorSelectedPortions.toString()
                                                                        isPortionsManuallyModified = true // 标记为手动修改
                                                                        // 更新光标显示时间
                                                                        lastInputTime = System.currentTimeMillis()
                                                                        cursorVisible = true
                                                                        
                                                                        // 同步更新所有已选择菜谱的槽位份数
                                                                        updateRecipePortionsForAllSelectedRecipes()
                                                                    }
                                                                },
                                                            contentAlignment = Alignment.Center
                                                        ) {
                                                            Text(
                                                                text = "+",
                                                                fontSize = 10.sp,
                                                                color = MaterialTheme.colorScheme.onSurface,
                                                                textAlign = TextAlign.Center,
                                                                lineHeight = 20.sp
                                                            )
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        
                                        // 第四行：单位食材、单位时间
                                        Row(
                                            modifier = Modifier.fillMaxWidth(),
                                            horizontalArrangement = Arrangement.SpaceBetween
                                        ) {
                                            Text(
                                                text = "单位食材: ${formatNumber(unitFood, 2)}",
                                                fontSize = 10.sp,
                                                fontWeight = FontWeight.Medium,
                                                color = MaterialTheme.colorScheme.onSurface,
                                                modifier = Modifier.weight(1f),
                                                textAlign = TextAlign.Start
                                            )
                                            Text(
                                                text = "单位时间: ${formatNumber(unitTime, 2)}",
                                                fontSize = 10.sp,
                                                fontWeight = FontWeight.Medium,
                                                color = MaterialTheme.colorScheme.onSurface,
                                                modifier = Modifier.weight(1f),
                                                textAlign = TextAlign.Start
                                            )
                                            // 同贵客双菜谱按钮
                                            OutlinedButton(
                                                onClick = { isDualRecipeExpanded = !isDualRecipeExpanded },
                                                modifier = Modifier
                                                    .weight(1f)
                                                    .height(20.dp)
                                                    .padding(start = 8.dp),
                                                colors = ButtonDefaults.outlinedButtonColors(
                                                    containerColor = MaterialTheme.colorScheme.primary,
                                                    contentColor = Color.White
                                                ),
                                                shape = RoundedCornerShape(4.dp),
                                                border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary),
                                                contentPadding = PaddingValues(horizontal = 4.dp, vertical = 0.dp)
                                            ) {
                                                Text(
                                                    text = "同贵客双菜谱",
                                                    fontSize = 8.sp,
                                                    fontWeight = FontWeight.Medium
                                                )
                                            }
                                        }
                                        
                                        // 第五行：原时间、总时间
                                        Row(
                                            modifier = Modifier.fillMaxWidth(),
                                            horizontalArrangement = Arrangement.Start
                                        ) {
                                            // 计算所有已选择菜谱的总时间
                                            val totalOriginalTime = remember(calculatorSelectedRecipes, calculatorRecipePortions) {
                                                var sum = 0.0
                                                for (i in 0 until 9) {
                                                    val recipe = calculatorSelectedRecipes.getOrNull(i)
                                                    val portions = calculatorRecipePortions.getOrNull(i) ?: 0
                                                    if (recipe != null && recipe.name.isNotEmpty() && portions > 0) {
                                                        sum += recipe.time * portions
                                                    }
                                                }
                                                sum
                                            }
                                            
                                            // 计算应用时间加成后的总时间
                                            val totalFinalTime = remember(totalOriginalTime, totalTimeBonus) {
                                                val timeMultiplier = (100.0 + totalTimeBonus) / 100.0
                                                totalOriginalTime * timeMultiplier
                                            }
                                            
                                            // 原时间：固定宽度，确保布局稳定
                                            Box(
                                                modifier = Modifier.width(120.dp),
                                                contentAlignment = Alignment.CenterStart
                                            ) {
                                                Text(
                                                    text = "原时间: ${formatTime(totalOriginalTime.toInt())}",
                                                    fontSize = 10.sp,
                                                    fontWeight = FontWeight.Medium,
                                                    color = MaterialTheme.colorScheme.onSurface,
                                                    textAlign = TextAlign.Start
                                                )
                                            }
                                            
                                            // 总时间：固定宽度，确保始终在固定位置显示
                                            Box(
                                                modifier = Modifier.width(120.dp),
                                                contentAlignment = Alignment.CenterStart
                                            ) {
                                                Text(
                                                    text = "总时间: ${formatTime(totalFinalTime.toInt())}",
                                                    fontSize = 10.sp,
                                                    fontWeight = FontWeight.Medium,
                                                    color = MaterialTheme.colorScheme.onSurface,
                                                    textAlign = TextAlign.Start
                                                )
                                            }
                                        }
                                        
                                        // 同贵客双菜谱展开内容
                                        if (isDualRecipeExpanded) {
                                            // 初始化和同步贵客率为当前计算器的贵客率
                                            LaunchedEffect(totalGuestRate) {
                                                if (dualRecipeGuestRate == 0.0) {
                                                    dualRecipeGuestRate = totalGuestRate
                                                }
                                            }
                                            
                                            // 当上边贵客率变化时，同步更新这个贵客率
                                            LaunchedEffect(totalGuestRate) {
                                                if (dualRecipeGuestRate != totalGuestRate && totalGuestRate > 0.0) {
                                                    dualRecipeGuestRate = totalGuestRate
                                                }
                                            }
                                            
                                            // 计算同贵客双菜谱数据（实时计算）
                                            val dualRecipeResult = calculateDualRecipeData(dualRecipeGuestRate, dualRecipeStarLevel1, dualRecipeQuantity1, dualRecipeStarLevel2, dualRecipeQuantity2)
                                            
                                            Column(
                                                modifier = Modifier
                                                    .fillMaxWidth()
                                                    .padding(top = 1.dp),
                                                verticalArrangement = Arrangement.spacedBy(0.dp)
                                            ) {
                                                // 标题
                                                Text(
                                                    text = "同贵客双菜谱实现贵客必来 品级默认可",
                                                    fontSize = 12.sp,
                                                    fontWeight = FontWeight.Bold,
                                                    color = Color.Blue,
                                                    modifier = Modifier.fillMaxWidth(),
                                                    textAlign = TextAlign.Center
                                                )
                                                
                                                // 贵客率输入行
                                                Row(
                                                    modifier = Modifier.fillMaxWidth(),
                                                    verticalAlignment = Alignment.CenterVertically,
                                                    horizontalArrangement = Arrangement.SpaceEvenly
                                                ) {
                                                    // 第一列：贵客率（与星级对齐）
                                                    Row(
                                                        modifier = Modifier.weight(1f),
                                                        verticalAlignment = Alignment.CenterVertically,
                                                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                                                    ) {
                                                        Text(
                                                            text = "贵客率",
                                                            fontSize = 10.sp,
                                                            color = Color.Black
                                                        )
                                                        
                                                        // 贵客率输入框状态
                                                        var guestRateInputText by remember { mutableStateOf(formatNumber(dualRecipeGuestRate, 1)) }
                                                        var guestRateFocusRequester by remember { mutableStateOf(FocusRequester()) }
                                                        var guestRateIsFocused by remember { mutableStateOf(false) }
                                                        var guestRateCursorVisible by remember { mutableStateOf(false) }
                                                        var guestRateLastInputTime by remember { mutableStateOf(0L) }
                                                        var guestRateInputFieldEnabled by remember { mutableStateOf(true) }
                                                        
                                                        // 2秒后自动隐藏光标（参考计算结果第三行份数逻辑）
                                                        LaunchedEffect(guestRateLastInputTime) {
                                                            if (guestRateLastInputTime > 0) {
                                                                delay(2000) // 2秒延迟
                                                                guestRateCursorVisible = false
                                                                // 失去焦点以隐藏选择指示器
                                                                guestRateFocusRequester.freeFocus()
                                                                // 暂时禁用输入框来清除选择状态
                                                                guestRateInputFieldEnabled = false
                                                                delay(50) // 短暂延迟
                                                                guestRateInputFieldEnabled = true
                                                            }
                                                        }
                                                        
                                                        // 贵客率输入框
                                                        Box(
                                                            modifier = Modifier
                                                                .width(37.dp)
                                                                .height(16.dp)
                                                                .border(
                                                                    width = 1.dp,
                                                                    color = MaterialTheme.colorScheme.outline,
                                                                    shape = RoundedCornerShape(2.dp)
                                                                )
                                                                .background(
                                                                    color = MaterialTheme.colorScheme.surface,
                                                                    shape = RoundedCornerShape(2.dp)
                                                                )
                                                                .clickable(
                                                                    interactionSource = remember { MutableInteractionSource() },
                                                                    indication = null
                                                                ) {
                                                                    // 点击输入框时聚焦
                                                                    guestRateFocusRequester.requestFocus()
                                                                },
                                                            contentAlignment = Alignment.Center
                                                        ) {
                                                            BasicTextField(
                                                                value = guestRateInputText,
                                                                enabled = guestRateInputFieldEnabled,
                                                                onValueChange = { newValue ->
                                                                    // 允许输入数字和小数点
                                                                    val filteredValue = newValue.filter { it.isDigit() || it == '.' }
                                                                    guestRateInputText = filteredValue
                                                                    
                                                                    // 更新最后输入时间，显示光标
                                                                    guestRateLastInputTime = System.currentTimeMillis()
                                                                    guestRateCursorVisible = true
                                                                    
                                                                    if (filteredValue.isNotEmpty() && filteredValue != ".") {
                                                                        val doubleValue = filteredValue.toDoubleOrNull()
                                                                        if (doubleValue != null) {
                                                                            // 限制最大值为999
                                                                            if (doubleValue > 999) {
                                                                                dualRecipeGuestRate = 999.0
                                                                                guestRateInputText = "999"
                                                                            } else {
                                                                                dualRecipeGuestRate = doubleValue
                                                                            }
                                                                        }
                                                                    }
                                                                },
                                                                textStyle = androidx.compose.ui.text.TextStyle(
                                                                    fontSize = 10.sp,
                                                                    fontWeight = FontWeight.Medium,
                                                                    color = MaterialTheme.colorScheme.onSurface,
                                                                    textAlign = TextAlign.Center,
                                                                    lineHeight = 10.sp
                                                                ),
                                                                singleLine = true,
                                                                modifier = Modifier
                                                                    .fillMaxSize()
                                                                    .focusRequester(guestRateFocusRequester)
                                                                    .onFocusChanged { focusState ->
                                                                        guestRateIsFocused = focusState.isFocused
                                                                        // 获得焦点时显示光标
                                                                        if (focusState.isFocused) {
                                                                            guestRateCursorVisible = true
                                                                            guestRateLastInputTime = System.currentTimeMillis()
                                                                        }
                                                                        // 失去焦点时处理输入值
                                                                        if (!focusState.isFocused) {
                                                                            if (guestRateInputText.isEmpty() || guestRateInputText.toDoubleOrNull() == null) {
                                                                                // 如果输入为空或无效，重置为当前值
                                                                                guestRateInputText = formatNumber(dualRecipeGuestRate, 1)
                                                                            } else {
                                                                                val doubleValue = guestRateInputText.toDoubleOrNull() ?: 0.0
                                                                                if (doubleValue > 999) {
                                                                                    dualRecipeGuestRate = 999.0
                                                                                    guestRateInputText = "999"
                                                                                } else if (doubleValue < 0) {
                                                                                    dualRecipeGuestRate = 0.0
                                                                                    guestRateInputText = "0"
                                                                                } else {
                                                                                    // 确保dualRecipeGuestRate与guestRateInputText同步
                                                                                    dualRecipeGuestRate = doubleValue
                                                                                }
                                                                            }
                                                                        }
                                                                    },
                                                                cursorBrush = if (guestRateCursorVisible) SolidColor(MaterialTheme.colorScheme.primary) else SolidColor(Color.Transparent)
                                                            ) { innerTextField ->
                                                                Box(
                                                                    modifier = Modifier.fillMaxSize(),
                                                                    contentAlignment = Alignment.Center
                                                                ) {
                                                                    innerTextField()
                                                                }
                                                            }
                                                        }
                                                        
                                                        // 同步输入框和状态
                                                        LaunchedEffect(dualRecipeGuestRate) {
                                                            val formatted = formatNumber(dualRecipeGuestRate, 1)
                                                            if (guestRateInputText != formatted && !guestRateInputText.endsWith(".")) {
                                                                guestRateInputText = formatted
                                                            }
                                                        }
                                                        
                                                        Text(
                                                            text = "%",
                                                            fontSize = 10.sp,
                                                            color = Color.Black
                                                        )
                                                    }
                                                    
                                                    // 第二列：占位（与份数对齐）
                                                    Box(modifier = Modifier.weight(1f))
                                                    
                                                    // 第三列：占位（与实际贵客率对齐）
                                                    Box(modifier = Modifier.weight(1f))
                                                }
                                                
                                                // 第一个菜谱行
                                                Row(
                                                    modifier = Modifier.fillMaxWidth(),
                                                    verticalAlignment = Alignment.CenterVertically,
                                                    horizontalArrangement = Arrangement.Start
                                                ) {
                                                    // 第一列：星级
                                                    Row(
                                                        modifier = Modifier.width(78.dp),
                                                        verticalAlignment = Alignment.CenterVertically,
                                                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                                                    ) {
                                                        Text(
                                                            text = "星级",
                                                            fontSize = 10.sp,
                                                            color = Color.Black
                                                        )
                                                        CalculatorStarLevelDropdown(
                                                            selectedStarLevel = dualRecipeStarLevel1,
                                                            onStarLevelSelected = { dualRecipeStarLevel1 = it },
                                                            modifier = Modifier
                                                                .width(50.dp)
                                                                .height(20.dp)
                                                        )
                                                    }
                                                    
                                                    Spacer(modifier = Modifier.width(15.dp))
                                                    
                                                    // 第二列：份数
                                                    Row(
                                                        modifier = Modifier.width(100.dp),
                                                        verticalAlignment = Alignment.CenterVertically,
                                                        horizontalArrangement = Arrangement.spacedBy(4.dp)
                                                    ) {
                                                        Text(
                                                            text = "份数",
                                                            fontSize = 10.sp,
                                                            color = Color.Black
                                                        )
                                                        
                                                        // 份数输入框状态
                                                        var inputText1 by remember { mutableStateOf(dualRecipeQuantity1.toString()) }
                                                        var focusRequester1 by remember { mutableStateOf(FocusRequester()) }
                                                        var isFocused1 by remember { mutableStateOf(false) }
                                                        var cursorVisible1 by remember { mutableStateOf(false) }
                                                        var lastInputTime1 by remember { mutableStateOf(0L) }
                                                        var inputFieldEnabled1 by remember { mutableStateOf(true) }
                                                        
                                                        // 2秒后自动隐藏光标（参考计算结果第三行份数逻辑）
                                                        LaunchedEffect(lastInputTime1) {
                                                            if (lastInputTime1 > 0) {
                                                                delay(2000) // 2秒延迟
                                                                cursorVisible1 = false
                                                                // 失去焦点以隐藏选择指示器
                                                                focusRequester1.freeFocus()
                                                                // 暂时禁用输入框来清除选择状态
                                                                inputFieldEnabled1 = false
                                                                delay(50) // 短暂延迟
                                                                inputFieldEnabled1 = true
                                                            }
                                                        }
                                                        
                                                        Row(
                                                            horizontalArrangement = Arrangement.spacedBy(4.dp)
                                                        ) {
                                                            // 减号按钮
                                                            OutlinedCard(
                                                                modifier = Modifier
                                                                    .width(16.dp)
                                                                    .height(20.dp),
                                                                border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
                                                                shape = RoundedCornerShape(4.dp)
                                                            ) {
                                                                Box(
                                                                    modifier = Modifier
                                                                        .fillMaxSize()
                                                                        .clickable {
                                                                            if (dualRecipeQuantity1 > 0) {
                                                                                dualRecipeQuantity1--
                                                                                inputText1 = dualRecipeQuantity1.toString()
                                                                            }
                                                                        },
                                                                    contentAlignment = Alignment.Center
                                                                ) {
                                                                    Text(
                                                                        text = "-",
                                                                        fontSize = 10.sp,
                                                                        color = MaterialTheme.colorScheme.onSurface,
                                                                        textAlign = TextAlign.Center,
                                                                        lineHeight = 20.sp
                                                                    )
                                                                }
                                                            }
                                                            
                                                            // 中间的数字输入框
                                                            Box(
                                                                modifier = Modifier
                                                                    .width(32.dp)
                                                                    .height(20.dp)
                                                                    .border(
                                                                        width = 1.dp,
                                                                        color = MaterialTheme.colorScheme.outline,
                                                                        shape = RoundedCornerShape(2.dp)
                                                                    )
                                                                    .background(
                                                                        color = MaterialTheme.colorScheme.surface,
                                                                        shape = RoundedCornerShape(2.dp)
                                                                    )
                                                                    .clickable(
                                                                        interactionSource = remember { MutableInteractionSource() },
                                                                        indication = null
                                                                    ) {
                                                                        // 点击输入框时聚焦
                                                                        focusRequester1.requestFocus()
                                                                    },
                                                                contentAlignment = Alignment.Center
                                                            ) {
                                                                BasicTextField(
                                                                    value = inputText1,
                                                                    enabled = inputFieldEnabled1,
                                                                    onValueChange = { newValue ->
                                                                        val filteredValue = newValue.filter { it.isDigit() }
                                                                        inputText1 = filteredValue
                                                                        
                                                                        // 更新最后输入时间，显示光标
                                                                        lastInputTime1 = System.currentTimeMillis()
                                                                        cursorVisible1 = true
                                                                        
                                                                        if (filteredValue.isNotEmpty()) {
                                                                            val intValue = filteredValue.toIntOrNull()
                                                                            if (intValue != null) {
                                                                                // 限制最大值为99
                                                                                if (intValue > 99) {
                                                                                    dualRecipeQuantity1 = 99
                                                                                    inputText1 = "99"
                                                                                } else {
                                                                                    dualRecipeQuantity1 = intValue
                                                                                }
                                                                            }
                                                                        }
                                                                    },
                                                                    textStyle = androidx.compose.ui.text.TextStyle(
                                                                        fontSize = 10.sp,
                                                                        fontWeight = FontWeight.Medium,
                                                                        color = MaterialTheme.colorScheme.onSurface,
                                                                        textAlign = TextAlign.Center,
                                                                        lineHeight = 10.sp
                                                                    ),
                                                                    singleLine = true,
                                                                    modifier = Modifier
                                                                        .fillMaxSize()
                                                                        .focusRequester(focusRequester1)
                                                                        .onFocusChanged { focusState ->
                                                                            isFocused1 = focusState.isFocused
                                                                            // 获得焦点时显示光标
                                                                            if (focusState.isFocused) {
                                                                                cursorVisible1 = true
                                                                                lastInputTime1 = System.currentTimeMillis()
                                                                            }
                                                                            // 失去焦点时处理输入值
                                                                            if (!focusState.isFocused) {
                                                                                if (inputText1.isEmpty() || inputText1.toIntOrNull() == null) {
                                                                                    // 如果输入为空或无效，重置为当前值
                                                                                    inputText1 = dualRecipeQuantity1.toString()
                                                                                } else {
                                                                                    val intValue = inputText1.toIntOrNull() ?: 0
                                                                                    if (intValue > 99) {
                                                                                        dualRecipeQuantity1 = 99
                                                                                        inputText1 = "99"
                                                                                    } else if (intValue < 0) {
                                                                                        dualRecipeQuantity1 = 0
                                                                                        inputText1 = "0"
                                                                                    } else {
                                                                                        // 确保dualRecipeQuantity1与inputText1同步
                                                                                        dualRecipeQuantity1 = intValue
                                                                                    }
                                                                                }
                                                                            }
                                                                        },
                                                                    cursorBrush = if (cursorVisible1) SolidColor(MaterialTheme.colorScheme.primary) else SolidColor(Color.Transparent)
                                                                ) { innerTextField ->
                                                                    Box(
                                                                        modifier = Modifier.fillMaxSize(),
                                                                        contentAlignment = Alignment.Center
                                                                    ) {
                                                                        innerTextField()
                                                                    }
                                                                }
                                                            }
                                                            
                                                            // 同步inputText和dualRecipeQuantity1
                                                            LaunchedEffect(dualRecipeQuantity1) {
                                                                if (inputText1 != dualRecipeQuantity1.toString()) {
                                                                    inputText1 = dualRecipeQuantity1.toString()
                                                                }
                                                            }
                                                            
                                                            // 加号按钮
                                                            OutlinedCard(
                                                                modifier = Modifier
                                                                    .width(16.dp)
                                                                    .height(20.dp),
                                                                border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
                                                                shape = RoundedCornerShape(4.dp)
                                                            ) {
                                                                Box(
                                                                    modifier = Modifier
                                                                        .fillMaxSize()
                                                                        .clickable {
                                                                            if (dualRecipeQuantity1 < 99) {
                                                                                dualRecipeQuantity1++
                                                                                inputText1 = dualRecipeQuantity1.toString()
                                                                            }
                                                                        },
                                                                    contentAlignment = Alignment.Center
                                                                ) {
                                                                    Text(
                                                                        text = "+",
                                                                        fontSize = 10.sp,
                                                                        color = MaterialTheme.colorScheme.onSurface,
                                                                        textAlign = TextAlign.Center,
                                                                        lineHeight = 20.sp
                                                                    )
                                                                }
                                                            }
                                                        }
                                                    }
                                                    
                                                    Spacer(modifier = Modifier.width(12.dp))
                                                    
                                                    // 第三列：实际贵客率（固定位置，数值右对齐）
                                                    Row(
                                                        modifier = Modifier.fillMaxWidth(),
                                                        verticalAlignment = Alignment.CenterVertically,
                                                        horizontalArrangement = Arrangement.SpaceBetween
                                                    ) {
                                                        Text(
                                                            text = "实际贵客率:",
                                                            fontSize = 10.sp,
                                                            color = Color.Black
                                                        )
                                                        Text(
                                                            text = "${formatNumber(dualRecipeResult.actualGuestRate1, 2)}%",
                                                            fontSize = 10.sp,
                                                            color = Color.Black,
                                                            textAlign = TextAlign.End
                                                        )
                                                    }
                                                }
                                                
                                                // 第二个菜谱行
                                                Row(
                                                    modifier = Modifier.fillMaxWidth(),
                                                    verticalAlignment = Alignment.CenterVertically,
                                                    horizontalArrangement = Arrangement.Start
                                                ) {
                                                    // 第一列：星级
                                                    Row(
                                                        modifier = Modifier.width(78.dp),
                                                        verticalAlignment = Alignment.CenterVertically,
                                                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                                                    ) {
                                                        Text(
                                                            text = "星级",
                                                            fontSize = 10.sp,
                                                            color = Color.Black
                                                        )
                                                        CalculatorStarLevelDropdown(
                                                            selectedStarLevel = dualRecipeStarLevel2,
                                                            onStarLevelSelected = { dualRecipeStarLevel2 = it },
                                                            modifier = Modifier
                                                                .width(50.dp)
                                                                .height(20.dp)
                                                        )
                                                    }
                                                    
                                                    Spacer(modifier = Modifier.width(15.dp))
                                                    
                                                    // 第二列：份数
                                                    Row(
                                                        modifier = Modifier.width(100.dp),
                                                        verticalAlignment = Alignment.CenterVertically,
                                                        horizontalArrangement = Arrangement.spacedBy(4.dp)
                                                    ) {
                                                        Text(
                                                            text = "份数",
                                                            fontSize = 10.sp,
                                                            color = Color.Black
                                                        )
                                                        
                                                        // 份数输入框状态
                                                        var inputText2 by remember { mutableStateOf(dualRecipeQuantity2.toString()) }
                                                        var focusRequester2 by remember { mutableStateOf(FocusRequester()) }
                                                        var isFocused2 by remember { mutableStateOf(false) }
                                                        var cursorVisible2 by remember { mutableStateOf(false) }
                                                        var lastInputTime2 by remember { mutableStateOf(0L) }
                                                        var inputFieldEnabled2 by remember { mutableStateOf(true) }
                                                        
                                                        // 2秒后自动隐藏光标（参考计算结果第三行份数逻辑）
                                                        LaunchedEffect(lastInputTime2) {
                                                            if (lastInputTime2 > 0) {
                                                                delay(2000) // 2秒延迟
                                                                cursorVisible2 = false
                                                                // 失去焦点以隐藏选择指示器
                                                                focusRequester2.freeFocus()
                                                                // 暂时禁用输入框来清除选择状态
                                                                inputFieldEnabled2 = false
                                                                delay(50) // 短暂延迟
                                                                inputFieldEnabled2 = true
                                                            }
                                                        }
                                                        
                                                        Row(
                                                            horizontalArrangement = Arrangement.spacedBy(4.dp)
                                                        ) {
                                                            // 减号按钮
                                                            OutlinedCard(
                                                                modifier = Modifier
                                                                    .width(16.dp)
                                                                    .height(20.dp),
                                                                border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
                                                                shape = RoundedCornerShape(4.dp)
                                                            ) {
                                                                Box(
                                                                    modifier = Modifier
                                                                        .fillMaxSize()
                                                                        .clickable {
                                                                            if (dualRecipeQuantity2 > 0) {
                                                                                dualRecipeQuantity2--
                                                                                inputText2 = dualRecipeQuantity2.toString()
                                                                            }
                                                                        },
                                                                    contentAlignment = Alignment.Center
                                                                ) {
                                                                    Text(
                                                                        text = "-",
                                                                        fontSize = 10.sp,
                                                                        color = MaterialTheme.colorScheme.onSurface,
                                                                        textAlign = TextAlign.Center,
                                                                        lineHeight = 20.sp
                                                                    )
                                                                }
                                                            }
                                                            
                                                            // 中间的数字输入框
                                                            Box(
                                                                modifier = Modifier
                                                                    .width(32.dp)
                                                                    .height(20.dp)
                                                                    .border(
                                                                        width = 1.dp,
                                                                        color = MaterialTheme.colorScheme.outline,
                                                                        shape = RoundedCornerShape(2.dp)
                                                                    )
                                                                    .background(
                                                                        color = MaterialTheme.colorScheme.surface,
                                                                        shape = RoundedCornerShape(2.dp)
                                                                    )
                                                                    .clickable(
                                                                        interactionSource = remember { MutableInteractionSource() },
                                                                        indication = null
                                                                    ) {
                                                                        // 点击输入框时聚焦
                                                                        focusRequester2.requestFocus()
                                                                    },
                                                                contentAlignment = Alignment.Center
                                                            ) {
                                                                BasicTextField(
                                                                    value = inputText2,
                                                                    enabled = inputFieldEnabled2,
                                                                    onValueChange = { newValue ->
                                                                        val filteredValue = newValue.filter { it.isDigit() }
                                                                        inputText2 = filteredValue
                                                                        
                                                                        // 更新最后输入时间，显示光标
                                                                        lastInputTime2 = System.currentTimeMillis()
                                                                        cursorVisible2 = true
                                                                        
                                                                        if (filteredValue.isNotEmpty()) {
                                                                            val intValue = filteredValue.toIntOrNull()
                                                                            if (intValue != null) {
                                                                                // 限制最大值为99
                                                                                if (intValue > 99) {
                                                                                    dualRecipeQuantity2 = 99
                                                                                    inputText2 = "99"
                                                                                } else {
                                                                                    dualRecipeQuantity2 = intValue
                                                                                }
                                                                            }
                                                                        }
                                                                    },
                                                                    textStyle = androidx.compose.ui.text.TextStyle(
                                                                        fontSize = 10.sp,
                                                                        fontWeight = FontWeight.Medium,
                                                                        color = MaterialTheme.colorScheme.onSurface,
                                                                        textAlign = TextAlign.Center,
                                                                        lineHeight = 10.sp
                                                                    ),
                                                                    singleLine = true,
                                                                    modifier = Modifier
                                                                        .fillMaxSize()
                                                                        .focusRequester(focusRequester2)
                                                                        .onFocusChanged { focusState ->
                                                                            isFocused2 = focusState.isFocused
                                                                            // 获得焦点时显示光标
                                                                            if (focusState.isFocused) {
                                                                                cursorVisible2 = true
                                                                                lastInputTime2 = System.currentTimeMillis()
                                                                            }
                                                                            // 失去焦点时处理输入值
                                                                            if (!focusState.isFocused) {
                                                                                if (inputText2.isEmpty() || inputText2.toIntOrNull() == null) {
                                                                                    // 如果输入为空或无效，重置为当前值
                                                                                    inputText2 = dualRecipeQuantity2.toString()
                                                                                } else {
                                                                                    val intValue = inputText2.toIntOrNull() ?: 0
                                                                                    if (intValue > 99) {
                                                                                        dualRecipeQuantity2 = 99
                                                                                        inputText2 = "99"
                                                                                    } else if (intValue < 0) {
                                                                                        dualRecipeQuantity2 = 0
                                                                                        inputText2 = "0"
                                                                                    } else {
                                                                                        // 确保dualRecipeQuantity2与inputText2同步
                                                                                        dualRecipeQuantity2 = intValue
                                                                                    }
                                                                                }
                                                                            }
                                                                        },
                                                                    cursorBrush = if (cursorVisible2) SolidColor(MaterialTheme.colorScheme.primary) else SolidColor(Color.Transparent)
                                                                ) { innerTextField ->
                                                                    Box(
                                                                        modifier = Modifier.fillMaxSize(),
                                                                        contentAlignment = Alignment.Center
                                                                    ) {
                                                                        innerTextField()
                                                                    }
                                                                }
                                                            }
                                                            
                                                            // 同步inputText和dualRecipeQuantity2
                                                            LaunchedEffect(dualRecipeQuantity2) {
                                                                if (inputText2 != dualRecipeQuantity2.toString()) {
                                                                    inputText2 = dualRecipeQuantity2.toString()
                                                                }
                                                            }
                                                            
                                                            // 加号按钮
                                                            OutlinedCard(
                                                                modifier = Modifier
                                                                    .width(16.dp)
                                                                    .height(20.dp),
                                                                border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
                                                                shape = RoundedCornerShape(4.dp)
                                                            ) {
                                                                Box(
                                                                    modifier = Modifier
                                                                        .fillMaxSize()
                                                                        .clickable {
                                                                            if (dualRecipeQuantity2 < 99) {
                                                                                dualRecipeQuantity2++
                                                                                inputText2 = dualRecipeQuantity2.toString()
                                                                            }
                                                                        },
                                                                    contentAlignment = Alignment.Center
                                                                ) {
                                                                    Text(
                                                                        text = "+",
                                                                        fontSize = 10.sp,
                                                                        color = MaterialTheme.colorScheme.onSurface,
                                                                        textAlign = TextAlign.Center,
                                                                        lineHeight = 20.sp
                                                                    )
                                                                }
                                                            }
                                                        }
                                                    }
                                                    
                                                    Spacer(modifier = Modifier.width(12.dp))
                                                    
                                                    // 第三列：实际贵客率（固定位置，数值右对齐）
                                                    Row(
                                                        modifier = Modifier.fillMaxWidth(),
                                                        verticalAlignment = Alignment.CenterVertically,
                                                        horizontalArrangement = Arrangement.SpaceBetween
                                                    ) {
                                                        Text(
                                                            text = "实际贵客率:",
                                                            fontSize = 10.sp,
                                                            color = Color.Black
                                                        )
                                                        Text(
                                                            text = "${formatNumber(dualRecipeResult.actualGuestRate2, 2)}%",
                                                            fontSize = 10.sp,
                                                            color = Color.Black,
                                                            textAlign = TextAlign.End
                                                        )
                                                    }
                                                }
                                                
                                                // 符文A、符文B、撒币和该贵客实际贵客率单行显示
                                                Row(
                                                    modifier = Modifier
                                                        .fillMaxWidth()
                                                        .padding(top = 4.dp),
                                                    horizontalArrangement = Arrangement.Start,
                                                    verticalAlignment = Alignment.CenterVertically
                                                ) {
                                                    // 符文A 紧凑显示
                                                    Row(
                                                        modifier = Modifier.width(65.dp),
                                                        horizontalArrangement = Arrangement.Start
                                                    ) {
                                                        Text(
                                                            text = "符文A ${formatNumber(dualRecipeResult.runeAProbability, 2)}%",
                                                            fontSize = 9.sp,
                                                            color = Color.Black,
                                                            textAlign = TextAlign.Start,
                                                            maxLines = 1,
                                                            softWrap = false
                                                        )
                                                    }
                                                    
                                                    // 符文B 紧凑显示
                                                    Row(
                                                        modifier = Modifier.width(66.dp),
                                                        horizontalArrangement = Arrangement.Start
                                                    ) {
                                                        Text(
                                                            text = "符文B ${formatNumber(dualRecipeResult.runeBProbability, 2)}%",
                                                            fontSize = 9.sp,
                                                            color = Color.Black,
                                                            textAlign = TextAlign.Start,
                                                            maxLines = 1,
                                                            softWrap = false
                                                        )
                                                    }
                                                    
                                                    // 撒币 紧凑显示
                                                    Row(
                                                        modifier = Modifier.width(58.dp),
                                                        horizontalArrangement = Arrangement.Start
                                                    ) {
                                                        Text(
                                                            text = "撒币 ${formatNumber(dualRecipeResult.scatterProbability, 2)}%",
                                                            fontSize = 9.sp,
                                                            color = Color.Black,
                                                            textAlign = TextAlign.Start,
                                                            maxLines = 1,
                                                            softWrap = false
                                                        )
                                                    }
                                                    
                                                    // 减少间距让该贵客实际贵客率往左移
                                                    
                                                    // 该贵客实际贵客率 描述位置固定，数值右对齐
                                                    Row(
                                                        modifier = Modifier.fillMaxWidth(),
                                                        horizontalArrangement = Arrangement.SpaceBetween,
                                                        verticalAlignment = Alignment.CenterVertically
                                                    ) {
                                                        Text(
                                                            text = "该贵客实际贵客率:",
                                                            fontSize = 9.sp,
                                                            color = Color.Black,
                                                            maxLines = 1,
                                                            softWrap = false
                                                        )
                                                        
                                                        Text(
                                                            text = "${formatNumber(dualRecipeResult.totalGuestRate, 2)}%",
                                                            fontSize = 9.sp,
                                                            color = if (dualRecipeResult.totalGuestRate > 100.0) Color.Red else Color.Black,
                                                            maxLines = 1,
                                                            softWrap = false,
                                                            textAlign = TextAlign.End
                                                        )
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        
                        // 按钮行：清空全部 + 查询设置 + 一键查询
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            // 清空全部按钮
                            OutlinedButton(
                                onClick = {
                                    // 清空所有选择的数据
                                    calculatorSelectedChefs = emptyList()
                                    calculatorSelectedEquips = emptyList()
                                    calculatorSelectedRecipes = emptyList()
                                    calculatorSelectedAmbers = emptyList()
                                    calculatorSelectedLevels = emptyList()
                                    calculatorSelectedStarLevel = 5 // 重置为默认5星
                                    calculatorSelectedRank = "可" // 重置为默认可级
                                    calculatorSelectedPortions = 7 // 重置为默认7份
                                    isPortionsManuallyModified = false // 重置手动修改标记
                                    
                                    // 重置同贵客双菜谱区域的值
                                    dualRecipeStarLevel1 = 5 // 重置为默认5星
                                    dualRecipeQuantity1 = 7 // 重置为默认7份
                                    dualRecipeStarLevel2 = 5 // 重置为默认5星  
                                    dualRecipeQuantity2 = 7 // 重置为默认7份
                                    dualRecipeGuestRate = 0.0 // 重置贵客率为0
                                    // 不收起同贵客双菜谱展开区域，保持用户当前的展开状态
                                },
                                modifier = Modifier
                                    .weight(1f)
                                    .height(32.dp),
                                colors = ButtonDefaults.outlinedButtonColors(
                                    containerColor = MaterialTheme.colorScheme.error,
                                    contentColor = Color.White
                                ),
                                shape = RoundedCornerShape(8.dp),
                                border = BorderStroke(1.dp, MaterialTheme.colorScheme.error),
                                contentPadding = PaddingValues(0.dp)
                            ) {
                                Box(
                                    modifier = Modifier.fillMaxSize(),
                                    contentAlignment = Alignment.Center
                                ) {
                                    Text(
                                        "清空全部",
                                        fontSize = 12.sp,
                                        fontWeight = FontWeight.Medium
                                    )
                                }
                            }
                            
                            // 查询设置按钮
                            OutlinedButton(
                                onClick = { showSettingsDialog = true },
                                modifier = Modifier
                                    .weight(1f)
                                    .height(32.dp),
                                colors = ButtonDefaults.outlinedButtonColors(
                                    containerColor = Color.Gray,
                                    contentColor = Color.White
                                ),
                                shape = RoundedCornerShape(8.dp),
                                border = BorderStroke(1.dp, Color.Gray),
                                contentPadding = PaddingValues(0.dp)
                            ) {
                                Box(
                                    modifier = Modifier.fillMaxSize(),
                                    contentAlignment = Alignment.Center
                                ) {
                                    Text(
                                        "查询设置",
                                        fontSize = 12.sp,
                                        fontWeight = FontWeight.Medium
                                    )
                                }
                            }
                            
                            // 一键查询按钮
                            OutlinedButton(
                                onClick = {
                                    // 实现一键查询逻辑
                                    System.out.println("一键查询按钮被点击")
                                    
                                    // 打印厨师选择框中每个厨师的详细信息
                                    printSelectedChefsDetails()
                                    
                                    // 使用协程来执行一键查询，避免在Composable中直接调用
                                    kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Main).launch {
                                        try {
                                            System.out.println("开始执行一键查询")
                                            performOneClickQuery(
                                                gameData = gameData,
                                                skills = gameData?.skills ?: emptyList(),
                                                personalData = viewModel.personalData.value,
                                                settingsStorage = settingsStorage,
                                                defaultMaxLevelAmber = defaultMaxLevelAmber,
                                                ultimateSkills = ultimateSkills,
                                                useAllChefs = useAllChefs, // 传递使用全部厨师设置
                                                existingChefs = calculatorSelectedChefs, // 传递当前已选择的厨师
                                                calculatorLevels = calculatorSelectedLevels, // 传递厨师选择框中的等级配置
                                                calculatorAmbers = calculatorSelectedAmbers, // 传递厨师选择框中的心法盘配置
                                                calculatorEquips = calculatorSelectedEquips, // 传递厨师选择框中的厨具配置
                                                recipeLimits = recipeLimits, // 传递个人菜谱上限设置
                                                onResultUpdate = { result -> oneClickQueryResult = result },
                                                onProgressUpdate = { inProgress -> isOneClickQueryInProgress = inProgress },
                                                onSelectionUpdate = { chefs, equips, ambers, levels, recommendedRank ->
                                                    calculatorSelectedChefs = chefs
                                                    calculatorSelectedEquips = equips
                                                    calculatorSelectedAmbers = ambers
                                                    calculatorSelectedLevels = levels
                                                    // 如果有特殊技能，自动将品级设置为特级
                                                    if (recommendedRank == "特") {
                                                        calculatorSelectedRank = "特"
                                                        System.out.println("检测到特殊符文技能，自动将品级设置为特级")
                                                    }
                                                    // 调试信息：输出品级信息
                                                    System.out.println("onSelectionUpdate 接收到品级: $recommendedRank")
                                                },
                                                onRecipeUpdate = { recipesByChef, totalGuestRate -> 
                                                    System.out.println("=== onRecipeUpdate 回调被调用 ===")
                                                    System.out.println("recipesByChef: ${recipesByChef.mapValues { it.value.map { recipe -> recipe.name } }}")
                                                    System.out.println("totalGuestRate: $totalGuestRate")
                                                    
                                                    // 将菜谱按照厨师槽位正确分配
                                                    val newSelectedRecipes = mutableListOf<com.example.show_auto.data.Recipe>()
                                                    val newRecipePortions = mutableListOf<Int>() // 新增：存储每个菜谱的实际分配份数
                                                    
                                                    // 确保列表有足够的位置（3个厨师 × 3个菜谱槽位 = 9个位置）
                                                    repeat(9) { 
                                                        newSelectedRecipes.add(com.example.show_auto.data.Recipe())
                                                        newRecipePortions.add(0) // 默认0份
                                                    }
                                                    
                                                    // 将分配的菜谱按照厨师槽位填充，同时记录份数
                                                    recipesByChef.forEach { (chefIndex, recipes) ->
                                                        recipes.forEachIndexed { recipeIndex, recipe ->
                                                            val globalRecipeIndex = chefIndex * 3 + recipeIndex
                                                            if (globalRecipeIndex < 9) {
                                                                newSelectedRecipes[globalRecipeIndex] = recipe
                                                                // 检查该菜谱是否为强补菜谱
                                                                // 强补菜谱的特征：1-2星 + 短时间 + 没有符文
                                                                // 这里我们通过更精确的特征来判断
                                                                val isSupplementedRecipe = recipe.rarity in 1..2 && 
                                                                    recipe.time <= 300 // 5分钟以内的菜谱
                                                                
                                                                val finalQuantity = if (isSupplementedRecipe) {
                                                                    // 强补菜谱：份数始终为1
                                                                    System.out.println("检测到强补菜谱: ${recipe.name}，份数固定为1")
                                                                    1
                                                                } else {
                                                                    // 普通菜谱：正常计算份数
                                                                // 计算该菜谱的实际分配份数
                                                                // 使用传入的总贵客率来计算份数
                                                                    val calculatedQuantity = calculateRecipeQuantity(recipe, totalGuestRate, settingsStorage, false, recipeLimits)
                                                                
                                                                // 根据个人数据页面信息，查询该星级菜谱玩家最多能制作的份数
                                                                val maxPortions = calculateMaxRecipePortions(recipe, recipeLimits)
                                                                
                                                                // 如果查询必来模式时判断的份数大于最多能制作的份数，那么把份数统一设置为最多能制作的份数
                                                                    if (settingsStorage.getCalculatorQueryMode()) {
                                                                    // 查询效率模式：直接使用计算出的份数
                                                                    calculatedQuantity
                                                                } else {
                                                                    // 查询必来模式：应用个人份数限制
                                                                    minOf(calculatedQuantity, maxPortions)
                                                                    }
                                                                }
                                                                
                                                                newRecipePortions[globalRecipeIndex] = finalQuantity
                                                                if (isSupplementedRecipe) {
                                                                    System.out.println("槽位$globalRecipeIndex 分配菜谱 ${recipe.name}，强补菜谱，份数固定为1")
                                                                } else {
                                                                    // 重新计算用于日志显示
                                                                    val calculatedQuantity = calculateRecipeQuantity(recipe, totalGuestRate, settingsStorage, false, recipeLimits)
                                                                    val maxPortions = calculateMaxRecipePortions(recipe, recipeLimits)
                                                                System.out.println("槽位$globalRecipeIndex 分配菜谱 ${recipe.name}，计算份数: $calculatedQuantity, 个人上限: $maxPortions, 最终份数: $finalQuantity")
                                                                }
                                                            }
                                                        }
                                                    }
                                                    
                                                    // 未分配的槽位保持为0份，不更新
                                                    System.out.println("最终菜谱份数分配: ${newRecipePortions}")
                                                    
                                                    calculatorSelectedRecipes = newSelectedRecipes
                                                    calculatorRecipePortions = newRecipePortions // 新增：更新菜谱份数列表
                                                    
                                                    // 计算所有分配菜谱中份数最大的值，用于更新计算结果
                                                    val maxPortions = newRecipePortions.maxOrNull() ?: 0
                                                    // 如果查询的菜谱数量为0，使用默认值7；否则使用计算出的最大份数
                                                    val finalPortions = if (maxPortions == 0) 7 else maxPortions
                                                    // 一键查询总是更新份数，并重置手动修改标记
                                                    calculatorSelectedPortions = finalPortions
                                                    isPortionsManuallyModified = false // 重置手动修改标记
                                                    System.out.println("一键查询更新计算结果份数为: $finalPortions (原始值: $maxPortions)")
                                                    
                                                    // 应用个人份数限制后的最终份数
                                                    // 调试信息：检查弹窗触发条件
                                                    System.out.println("弹窗触发条件检查: finalPortions=$finalPortions, 查询模式=${if (settingsStorage.getCalculatorQueryMode()) "查询效率" else "查询必来"}")
                                                    
                                                    if (finalPortions > 0 && !settingsStorage.getCalculatorQueryMode()) {
                                                        System.out.println("满足前两个条件，继续检查")
                                                        // 查询必来模式：检查是否需要应用个人份数限制
                                                        val recipesWithLimits = newSelectedRecipes.filter { it.name.isNotEmpty() }
                                                        System.out.println("有菜谱的槽位数量: ${recipesWithLimits.size}")
                                                        
                                                        if (recipesWithLimits.isNotEmpty()) {
                                                            // 找到所有分配菜谱中个人上限最小的值
                                                            val minMaxPortions = recipesWithLimits.minOfOrNull { recipe ->
                                                                val maxPortions = calculateMaxRecipePortions(recipe, recipeLimits)
                                                                System.out.println("菜谱 ${recipe.name} 个人上限: $maxPortions")
                                                                maxPortions
                                                            } ?: finalPortions
                                                            
                                                            System.out.println("所有菜谱中个人上限最小值: $minMaxPortions")
                                                            
                                                            // 检查是否需要显示弹窗：如果计算出的份数超过个人上限，就显示弹窗
                                                            // 我们需要找到计算出的份数（在应用个人限制之前）
                                                            // 从日志可以看出，查询必来模式计算出的份数是24，但被限制为15
                                                            // 我们需要重新计算原始份数，或者从其他地方获取
                                                            val calculatedPortions = if (recipesWithLimits.isNotEmpty()) {
                                                                // 重新计算第一个菜谱的原始份数
                                                                val firstRecipe = recipesWithLimits.first()
                                                                val originalQuantity = calculateRecipeQuantity(firstRecipe, totalGuestRate, settingsStorage, false, recipeLimits)
                                                                System.out.println("重新计算原始份数: 菜谱=${firstRecipe.name}, 贵客率=$totalGuestRate%, 原始份数=$originalQuantity")
                                                                originalQuantity
                                                            } else {
                                                                0
                                                            }
                                                            System.out.println("计算出的份数: $calculatedPortions, 个人上限: $minMaxPortions")
                                                            
                                                            if (calculatedPortions > minMaxPortions) {
                                                                System.out.println("计算出的份数超过个人上限，准备显示弹窗")
                                                                
                                                                // 分析所有无法实现必来的星级菜谱
                                                                val starLimits = analyzeStarLevelLimits(recipesWithLimits, totalGuestRate, recipeLimits)
                                                                
                                                                val limitInfo = GuestArrivalLimitInfo(
                                                                    currentGuestRate = totalGuestRate,
                                                                    starLimits = starLimits
                                                                )
                                                                
                                                                guestArrivalLimitInfo = limitInfo
                                                                showGuestArrivalLimitDialog = true
                                                                
                                                                System.out.println("贵客必来份数限制提示: 当前贵客率${totalGuestRate}%, 分析星级限制: ${starLimits.joinToString { "${it.starLevel}星(${it.personalLimit}份<${it.requiredPortions}份)" }}")
                                                                System.out.println("弹窗状态已设置: showGuestArrivalLimitDialog=true")
                                                            } else {
                                                                System.out.println("计算出的份数未超过个人上限，不显示弹窗")
                                                            }
                                                            
                                                            // 如果最终份数超过个人上限，则限制为个人上限
                                                            if (finalPortions > minMaxPortions) {
                                                                calculatorSelectedPortions = minMaxPortions
                                                                System.out.println("应用个人份数限制: 最终份数从 $finalPortions 调整为 $minMaxPortions")
                                                                
                                                                // 分析所有无法实现必来的星级菜谱
                                                                val starLimits = analyzeStarLevelLimits(recipesWithLimits, totalGuestRate, recipeLimits)
                                                                
                                                                val limitInfo = GuestArrivalLimitInfo(
                                                                    currentGuestRate = totalGuestRate,
                                                                    starLimits = starLimits
                                                                )
                                                                
                                                                guestArrivalLimitInfo = limitInfo
                                                                showGuestArrivalLimitDialog = true
                                                                
                                                                System.out.println("贵客必来份数限制提示: 当前贵客率${totalGuestRate}%, 分析星级限制: ${starLimits.joinToString { "${it.starLevel}星(${it.personalLimit}份<${it.requiredPortions}份)" }}")
                                                            }
                                                        }
                                                    }
                                                    
                                                    System.out.println("一键查询完成，按厨师槽位自动填充菜谱:")
                                                    recipesByChef.forEach { (chefIndex, recipes) ->
                                                        System.out.println("  厨师槽位$chefIndex: ${recipes.map { it.name }}")
                                                    }
                                                    System.out.println("菜谱份数更新: ${newRecipePortions}")
                                                    System.out.println("计算结果份数更新为: $finalPortions (原始值: $maxPortions)")
                                                }
                                            )
                                        } catch (e: Exception) {
                                            System.out.println("一键查询执行失败: ${e.message}")
                                            e.printStackTrace()
                                            isOneClickQueryInProgress = false
                                        }
                                    }
                                },
                                enabled = !isOneClickQueryInProgress,
                                modifier = Modifier
                                    .weight(1f)
                                    .height(32.dp),
                                colors = ButtonDefaults.outlinedButtonColors(
                                    containerColor = if (isOneClickQueryInProgress) MaterialTheme.colorScheme.surfaceVariant else MaterialTheme.colorScheme.primary,
                                    contentColor = if (isOneClickQueryInProgress) MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.onPrimary
                                ),
                                shape = RoundedCornerShape(8.dp),
                                border = BorderStroke(1.dp, if (isOneClickQueryInProgress) MaterialTheme.colorScheme.outline else MaterialTheme.colorScheme.primary),
                                contentPadding = PaddingValues(0.dp)
                            ) {
                                Box(
                                    modifier = Modifier.fillMaxSize(),
                                    contentAlignment = Alignment.Center
                                ) {
                                    Text(
                                        if (isOneClickQueryInProgress) "计算中..." else "一键查询",
                                        fontSize = 12.sp,
                                        fontWeight = FontWeight.Medium
                                    )
                                }
                            }
                        }
                        
                        // 贵客必来份数限制提示弹窗
                        // 调试信息
                        System.out.println("弹窗状态检查: showGuestArrivalLimitDialog=$showGuestArrivalLimitDialog, guestArrivalLimitInfo=${guestArrivalLimitInfo != null}")
                        
                        if (showGuestArrivalLimitDialog && guestArrivalLimitInfo != null) {
                            System.out.println("显示弹窗: ${guestArrivalLimitInfo}")
                            GuestArrivalLimitDialog(
                                limitInfo = guestArrivalLimitInfo!!,
                                onDismiss = {
                                    showGuestArrivalLimitDialog = false
                                    guestArrivalLimitInfo = null
                                    System.out.println("弹窗已关闭")
                                },
                                onShowGuestRateTable = {
                                    showGuestArrivalLimitDialog = false // 关闭当前弹窗
                                    showGuestPortionTable = true // 直接打开贵客必来对照表页面
                                    System.out.println("打开贵客必来对照表")
                                }
                            )
                        }
                        
                        // 贵客必来份数对照表弹窗
                        if (showGuestPortionTable) {
                            GuestPortionTableDialog(
                                onDismiss = {
                                    showGuestPortionTable = false
                                    showGuestArrivalLimitDialog = true // 重新显示贵客必来份数限制弹窗
                                    System.out.println("贵客必来对照表弹窗已关闭，重新显示限制弹窗")
                                }
                            )
                        }
                        

                        
                        // 厨师、厨具、菜谱选择框
                        Column(
                            modifier = Modifier.fillMaxWidth(),
                            verticalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                                // 三列布局
                                Row(
                                    modifier = Modifier.fillMaxWidth(),
                                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                                ) {
                                    repeat(3) { columnIndex ->
                                        // 每一列
                                        Column(
                                            modifier = Modifier.weight(1f),
                                            verticalArrangement = Arrangement.spacedBy(4.dp)
                                        ) {
                                            // 厨师选择框
                                            CalculatorChefBox(
                                                chef = calculatorSelectedChefs.getOrNull(columnIndex),
                                                equip = calculatorSelectedEquips.getOrNull(columnIndex),
                                                skills = gameData?.skills ?: emptyList(),
                                                ultimateSkills = ultimateSkills,
                                                chefInteractionBonus = chefInteractions[columnIndex],
                                                gameData = gameData,
                                                personalData = viewModel.personalData.collectAsState().value,
                                                columnIndex = columnIndex,
                                                calculatorSelectedLevels = calculatorSelectedLevels,
                                                calculatorSelectedAmbers = calculatorSelectedAmbers,
                                                calculatorSelectedChefs = calculatorSelectedChefs,
                                                viewModel = viewModel,
                                                currentDefaultAllUltimate = currentDefaultAllUltimate,
                                                usePersonalData = usePersonalData,
                                                defaultMaxLevelAmber = defaultMaxLevelAmber,
                                                onClick = { 
                                                    calculatorDialogIndex = columnIndex
                                                    calculatorShowChefDialog = true 
                                                },
                                                onAmberButtonClick = {
                                                    // 切换心法盘选择框的展开状态
                                                    isAmberSelectionExpanded = !isAmberSelectionExpanded
                                                },
                                                modifier = Modifier.fillMaxWidth()
                                            )

                                            // 心法盘选择框布局（根据展开状态显示）
                                            if (isAmberSelectionExpanded) {
                                                val chef = calculatorSelectedChefs.getOrNull(columnIndex)
                                                val amberColors = if (chef != null && chef.diskDesc.isNotEmpty()) {
                                                    parseChefAmberColors(chef.diskDesc)
                                                } else {
                                                    emptyList()
                                                }
                                            
                                            // 第一行：等级选择框 + 心法盘选择框
                                            Row(
                                                modifier = Modifier.fillMaxWidth(),
                                                horizontalArrangement = Arrangement.spacedBy(4.dp)
                                            ) {
                                                // 等级选择框
                                                val maxLevel = when (chef?.rarity) {
                                                    5 -> 5
                                                    4 -> 4
                                                    3 -> 3
                                                    2 -> 3
                                                    1 -> 3
                                                    null -> 5 // 没有选择厨师时默认1-5级
                                                    else -> 3
                                                }
                                                val levels = (1..maxLevel).toList().reversed() // 降序
                                                
                                                CalculatorLevelDropdown(
                                                    levels = levels,
                                                    selectedLevel = calculatorSelectedLevels.getOrNull(columnIndex),
                                                    onLevelSelected = { level ->
                                                        val newSelectedLevels = calculatorSelectedLevels.toMutableList()
                                                        while (newSelectedLevels.size <= columnIndex) {
                                                            newSelectedLevels.add(null)
                                                        }
                                                        newSelectedLevels[columnIndex] = level
                                                        calculatorSelectedLevels = newSelectedLevels
                                                    },
                                                    chef = chef,
                                                    personalData = viewModel.personalData.collectAsState().value,
                                                    useMaxLevelAmber = defaultMaxLevelAmber,
                                                    modifier = Modifier.weight(1f)
                                                )
                                                
                                                // 第一个心法盘选择框
                                                val amberColor1 = amberColors.getOrNull(0) ?: ""
                                                val selectedAmber1 = calculatorSelectedAmbers
                                                    .getOrNull(columnIndex)
                                                    ?.getOrNull(0)
                                                
                                                val availableAmbers1 = if (amberColor1.isNotEmpty() && gameData != null) {
                                                    filterAmbersByColor(gameData!!.ambers, amberColor1)
                                                } else {
                                                    emptyList()
                                                }
                                                
                                                CalculatorAmberDropdown(
                                                    amber = selectedAmber1,
                                                    amberColor = amberColor1,
                                                    availableAmbers = availableAmbers1,
                                                    chef = chef,
                                                    amberIndex = 0,
                                                    useMaxLevelAmber = defaultMaxLevelAmber,
                                                    gameData = gameData,
                                                    onAmberSelected = { amber ->
                                                        val currentChefAmbers = calculatorSelectedAmbers.getOrNull(columnIndex)?.toMutableList() ?: mutableListOf()
                                                        while (currentChefAmbers.size <= 0) {
                                                            currentChefAmbers.add(null)
                                                        }
                                                        currentChefAmbers[0] = amber
                                                        
                                                        val newSelectedAmbers = calculatorSelectedAmbers.toMutableList()
                                                        while (newSelectedAmbers.size <= columnIndex) {
                                                            newSelectedAmbers.add(emptyList())
                                                        }
                                                        newSelectedAmbers[columnIndex] = currentChefAmbers
                                                        calculatorSelectedAmbers = newSelectedAmbers
                                                    },
                                                    onClearAmber = {
                                                        val currentChefAmbers = calculatorSelectedAmbers.getOrNull(columnIndex)?.toMutableList() ?: mutableListOf()
                                                        while (currentChefAmbers.size <= 0) {
                                                            currentChefAmbers.add(null)
                                                        }
                                                        currentChefAmbers[0] = null
                                                        
                                                        val newSelectedAmbers = calculatorSelectedAmbers.toMutableList()
                                                        while (newSelectedAmbers.size <= columnIndex) {
                                                            newSelectedAmbers.add(emptyList())
                                                        }
                                                        newSelectedAmbers[columnIndex] = currentChefAmbers
                                                        calculatorSelectedAmbers = newSelectedAmbers
                                                    },
                                                    enabled = amberColor1 != "绿", // 绿色心法盘位置不可选择
                                                    modifier = Modifier.weight(1f)
                                                )
                                            }
                                            

                                            
                                            // 第二行：两个心法盘选择框
                                            Row(
                                                modifier = Modifier.fillMaxWidth(),
                                                horizontalArrangement = Arrangement.spacedBy(4.dp)
                                            ) {
                                                // 第二个心法盘选择框
                                                val amberColor2 = amberColors.getOrNull(1) ?: ""
                                                val selectedAmber2 = calculatorSelectedAmbers
                                                    .getOrNull(columnIndex)
                                                    ?.getOrNull(1)
                                                
                                                val availableAmbers2 = if (amberColor2.isNotEmpty() && gameData != null) {
                                                    filterAmbersByColor(gameData!!.ambers, amberColor2)
                                                } else {
                                                    emptyList()
                                                }
                                                
                                                CalculatorAmberDropdown(
                                                    amber = selectedAmber2,
                                                    amberColor = amberColor2,
                                                    availableAmbers = availableAmbers2,
                                                    chef = chef,
                                                    amberIndex = 1,
                                                    useMaxLevelAmber = defaultMaxLevelAmber,
                                                    gameData = gameData,
                                                    onAmberSelected = { amber ->
                                                        val currentChefAmbers = calculatorSelectedAmbers.getOrNull(columnIndex)?.toMutableList() ?: mutableListOf()
                                                        while (currentChefAmbers.size <= 1) {
                                                            currentChefAmbers.add(null)
                                                        }
                                                        currentChefAmbers[1] = amber
                                                        
                                                        val newSelectedAmbers = calculatorSelectedAmbers.toMutableList()
                                                        while (newSelectedAmbers.size <= columnIndex) {
                                                            newSelectedAmbers.add(emptyList())
                                                        }
                                                        newSelectedAmbers[columnIndex] = currentChefAmbers
                                                        calculatorSelectedAmbers = newSelectedAmbers
                                                    },
                                                    onClearAmber = {
                                                        val currentChefAmbers = calculatorSelectedAmbers.getOrNull(columnIndex)?.toMutableList() ?: mutableListOf()
                                                        while (currentChefAmbers.size <= 1) {
                                                            currentChefAmbers.add(null)
                                                        }
                                                        currentChefAmbers[1] = null
                                                        
                                                        val newSelectedAmbers = calculatorSelectedAmbers.toMutableList()
                                                        while (newSelectedAmbers.size <= columnIndex) {
                                                            newSelectedAmbers.add(emptyList())
                                                        }
                                                        newSelectedAmbers[columnIndex] = currentChefAmbers
                                                        calculatorSelectedAmbers = newSelectedAmbers
                                                    },
                                                    enabled = amberColor2 != "绿", // 绿色心法盘位置不可选择
                                                    modifier = Modifier.weight(1f)
                                                )
                                                
                                                // 第三个心法盘选择框
                                                val amberColor3 = amberColors.getOrNull(2) ?: ""
                                                val selectedAmber3 = calculatorSelectedAmbers
                                                    .getOrNull(columnIndex)
                                                    ?.getOrNull(2)
                                                
                                                val availableAmbers3 = if (amberColor3.isNotEmpty() && gameData != null) {
                                                    filterAmbersByColor(gameData!!.ambers, amberColor3)
                                                } else {
                                                    emptyList()
                                                }
                                                
                                                CalculatorAmberDropdown(
                                                    amber = selectedAmber3,
                                                    amberColor = amberColor3,
                                                    availableAmbers = availableAmbers3,
                                                    chef = chef,
                                                    amberIndex = 2,
                                                    useMaxLevelAmber = defaultMaxLevelAmber,
                                                    gameData = gameData,
                                                    onAmberSelected = { amber ->
                                                        val currentChefAmbers = calculatorSelectedAmbers.getOrNull(columnIndex)?.toMutableList() ?: mutableListOf()
                                                        while (currentChefAmbers.size <= 2) {
                                                            currentChefAmbers.add(null)
                                                        }
                                                        currentChefAmbers[2] = amber
                                                        
                                                        val newSelectedAmbers = calculatorSelectedAmbers.toMutableList()
                                                        while (newSelectedAmbers.size <= columnIndex) {
                                                            newSelectedAmbers.add(emptyList())
                                                        }
                                                        newSelectedAmbers[columnIndex] = currentChefAmbers
                                                        calculatorSelectedAmbers = newSelectedAmbers
                                                    },
                                                    onClearAmber = {
                                                        val currentChefAmbers = calculatorSelectedAmbers.getOrNull(columnIndex)?.toMutableList() ?: mutableListOf()
                                                        while (currentChefAmbers.size <= 2) {
                                                            currentChefAmbers.add(null)
                                                        }
                                                        currentChefAmbers[2] = null
                                                        
                                                        val newSelectedAmbers = calculatorSelectedAmbers.toMutableList()
                                                        while (newSelectedAmbers.size <= columnIndex) {
                                                            newSelectedAmbers.add(emptyList())
                                                        }
                                                        newSelectedAmbers[columnIndex] = currentChefAmbers
                                                        calculatorSelectedAmbers = newSelectedAmbers
                                                    },
                                                    enabled = amberColor3 != "绿", // 绿色心法盘位置不可选择
                                                    modifier = Modifier.weight(1f)
                                                )
                                            }
                                        }

                                        // 厨具选择框
                                            CalculatorEquipBox(
                                                equip = calculatorSelectedEquips.getOrNull(columnIndex),
                                                skills = gameData?.skills ?: emptyList(),
                                                allRecipes = gameData?.recipes ?: emptyList(),
                                                onClick = { 
                                                    calculatorDialogIndex = columnIndex
                                                    calculatorShowEquipDialog = true 
                                                },
                                                modifier = Modifier.fillMaxWidth()
                                            )

                                            // 3个菜谱选择框
                                            repeat(3) { recipeIndex ->
                                                val globalRecipeIndex = columnIndex * 3 + recipeIndex
                                                CalculatorRecipeBox(
                                                    recipe = calculatorSelectedRecipes.getOrNull(globalRecipeIndex),
                                                    chef = calculatorSelectedChefs.getOrNull(columnIndex),
                                                    equip = calculatorSelectedEquips.getOrNull(columnIndex),
                                                    skills = gameData?.skills ?: emptyList(),
                                                    ultimateSkills = ultimateSkills,
                                                    recipeLimits = recipeLimits,
                                                    chefInteractionBonus = chefInteractions.getOrNull(columnIndex),
                                                    actualPortions = calculatorRecipePortions.getOrNull(globalRecipeIndex) ?: 0, // 如果没有分配份数，显示0份
                                                    gameData = gameData,
                                                    chefIndex = columnIndex, // 厨师在列表中的索引
                                                    chefAmbers = calculatorSelectedAmbers.getOrNull(columnIndex) ?: listOf(null, null, null), // 厨师的心法盘配置
                                                    chefLevel = calculatorSelectedLevels.getOrNull(columnIndex) ?: 1, // 厨师等级
                                                    defaultMaxLevelAmber = defaultMaxLevelAmber, // 心法盘默认满级设置
                                                    onClick = { 
                                                        calculatorDialogIndex = globalRecipeIndex
                                                        calculatorShowRecipeDialog = true 
                                                    },
                                                    modifier = Modifier.fillMaxWidth()
                                                )
                                            }
                                        }
                                    }
                                }
                                
                                Spacer(modifier = Modifier.height(16.dp))
                            }
                    }
                }
            }
        }
    }
    
    // 使用说明弹窗
    if (showUsageDialog) {
        UsageGuideDialog(
            onDismiss = { showUsageDialog = false },
            tabIndex = usageDialogTabIndex,
            onTabChange = { index -> usageDialogTabIndex = index }
        )
    }
    
    // 设置弹窗
    if (showSettingsDialog) {
        RuneSettingsDialog(
            settingsStorage = settingsStorage,
            onDismiss = { showSettingsDialog = false }
        )
    }
    
    // 贵客率计算器的选择对话框
    if (calculatorShowChefDialog) {
        val currentPersonalData = viewModel.personalData.collectAsState().value
        CalculatorChefSelectionDialog(
            chefs = gameData?.chefs ?: emptyList(),
            selectedChefs = calculatorSelectedChefs,
            skills = gameData?.skills ?: emptyList(),
            gameData = gameData,
            personalData = currentPersonalData,
            dialogIndex = calculatorDialogIndex,
            defaultMaxLevelAmber = defaultMaxLevelAmber,
            onChefSelected = { chef ->
                val mutableList = calculatorSelectedChefs.toMutableList()
                // 确保列表有足够的位置
                while (mutableList.size <= calculatorDialogIndex) {
                    mutableList.add(com.example.show_auto.data.Chef())
                }
                mutableList[calculatorDialogIndex] = chef
                calculatorSelectedChefs = mutableList
                
                // 获取游戏数据，供后续逻辑使用
                val currentGameData = gameData
                
                // 根据"启用厨具遗玉"设置决定是否自动设置厨具选择框
                if (usePersonalData) {
                    val chefEquipId = currentPersonalData?.chefs?.get(chef.chefId)?.equip
                    val equipMutableList = calculatorSelectedEquips.toMutableList()
                    // 确保厨具列表有足够的位置
                    while (equipMutableList.size <= calculatorDialogIndex) {
                        equipMutableList.add(com.example.show_auto.data.Equip())
                    }
                    
                    if (chefEquipId != null && currentGameData != null) {
                        val equip = currentGameData.equips.find { it.equipId == chefEquipId.toString() }
                        if (equip != null) {
                            equipMutableList[calculatorDialogIndex] = equip
                        } else {
                            equipMutableList[calculatorDialogIndex] = com.example.show_auto.data.Equip() // 设置为空厨具
                        }
                    } else {
                        equipMutableList[calculatorDialogIndex] = com.example.show_auto.data.Equip() // 设置为空厨具
                    }
                    calculatorSelectedEquips = equipMutableList
                } else {
                    // 当"启用厨具遗玉"关闭时，不自动设置厨具，保持当前选择或设置为空
                    val equipMutableList = calculatorSelectedEquips.toMutableList()
                    while (equipMutableList.size <= calculatorDialogIndex) {
                        equipMutableList.add(com.example.show_auto.data.Equip())
                    }
                    // 不改变当前厨具选择，保持用户之前的选择
                    calculatorSelectedEquips = equipMutableList
                }
                
                // 根据"启用厨具遗玉"设置决定是否自动设置心法盘等级和心法盘
                if (usePersonalData) {
                    val personalChef = currentPersonalData?.chefs?.get(chef.chefId)
                    
                    // 设置等级：如果开启心法盘默认满级，则根据厨师星级设置满级
                    val levelMutableList = calculatorSelectedLevels.toMutableList()
                    while (levelMutableList.size <= calculatorDialogIndex) {
                        levelMutableList.add(null)
                    }
                    levelMutableList[calculatorDialogIndex] = if (defaultMaxLevelAmber) {
                        // 根据厨师星级设置心法盘等级
                        when (chef.rarity) {
                            5 -> 5
                            4 -> 4
                            else -> 3
                        }
                    } else if (personalChef?.dlv != null && personalChef.dlv > 0) {
                        personalChef.dlv
                    } else {
                        1 // 默认1级
                    }
                    calculatorSelectedLevels = levelMutableList
                    
                    // 设置心法盘：总是重置为空或实际数据
                    val amberMutableList = calculatorSelectedAmbers.toMutableList()
                    while (amberMutableList.size <= calculatorDialogIndex) {
                        amberMutableList.add(emptyList())
                    }
                    
                    if (personalChef?.ambers != null && personalChef.ambers.isNotEmpty() && currentGameData != null) {
                        // 如果有心法盘数据，设置实际数据
                        val chefAmbers = mutableListOf<com.example.show_auto.data.Amber?>()
                        personalChef.ambers.forEach { amberId ->
                            val amber = currentGameData.ambers.find { it.amberId == amberId.toString() }
                            chefAmbers.add(amber)
                        }
                        // 确保有3个位置
                        while (chefAmbers.size < 3) {
                            chefAmbers.add(null)
                        }
                        
                        // 如果开启了心法盘默认满级，则对所有蓝色心法盘位置使用满朋陨
                        if (defaultMaxLevelAmber) {
                            val finalAmbers = applyMaxLevelAmberToBluePositions(chef, chefAmbers, currentGameData, true)
                            
                            // 调试信息：输出心法盘更新信息
                            System.out.println("手动选择厨师 ${chef.name} 心法盘默认满级开启，应用满朋陨:")
                            System.out.println("  原始心法盘: $chefAmbers")
                            System.out.println("  最终心法盘: $finalAmbers")
                            
                            amberMutableList[calculatorDialogIndex] = finalAmbers.take(3)
                        } else {
                            amberMutableList[calculatorDialogIndex] = chefAmbers.take(3)
                        }
                    } else {
                        // 如果没有心法盘数据，设置默认数据
                        val defaultAmbers = mutableListOf<com.example.show_auto.data.Amber?>(null, null, null)
                        
                        // 如果开启了心法盘默认满级，则对所有蓝色心法盘位置使用满朋陨
                        if (defaultMaxLevelAmber && currentGameData != null) {
                            val finalAmbers = applyMaxLevelAmberToBluePositions(chef, defaultAmbers, currentGameData, true)
                            
                            // 调试信息：输出心法盘更新信息
                            System.out.println("手动选择厨师 ${chef.name} 心法盘默认满级开启，应用满朋陨:")
                            System.out.println("  原始心法盘: $defaultAmbers")
                            System.out.println("  最终心法盘: $finalAmbers")
                            
                            amberMutableList[calculatorDialogIndex] = finalAmbers
                        } else {
                            amberMutableList[calculatorDialogIndex] = defaultAmbers
                        }
                    }
                    calculatorSelectedAmbers = amberMutableList
                } else {
                    // 当"启用厨具遗玉"关闭时，不自动设置心法盘等级和心法盘，保持当前选择
                    val levelMutableList = calculatorSelectedLevels.toMutableList()
                    while (levelMutableList.size <= calculatorDialogIndex) {
                        levelMutableList.add(null)
                    }
                    // 但是，如果开启了心法盘默认满级，即使"启用厨具遗玉"关闭，也要设置相应的等级
                    if (defaultMaxLevelAmber) {
                        // 根据厨师星级设置心法盘等级
                        levelMutableList[calculatorDialogIndex] = when (chef.rarity) {
                            5 -> 5
                            4 -> 4
                            else -> 3
                        }
                    } else {
                        // 不改变当前等级选择，保持用户之前的选择
                        // 这里不需要做任何改变，因为上面已经初始化了空列表
                    }
                    
                    calculatorSelectedLevels = levelMutableList
                    
                    val amberMutableList = calculatorSelectedAmbers.toMutableList()
                    while (amberMutableList.size <= calculatorDialogIndex) {
                        amberMutableList.add(emptyList())
                    }
                    
                    // 但是，如果开启了心法盘默认满级，即使"启用厨具遗玉"关闭，也要设置满级满朋陨
                    if (defaultMaxLevelAmber && currentGameData != null) {
                        // 创建默认的心法盘列表（空的心法盘）
                        val defaultAmbers = mutableListOf<com.example.show_auto.data.Amber?>(null, null, null)
                        
                        // 对所有蓝色心法盘位置使用满朋陨
                        applyMaxLevelAmberToBluePositions(chef, defaultAmbers, currentGameData, true)
                        
                        amberMutableList[calculatorDialogIndex] = defaultAmbers
                    } else {
                        // 不改变当前心法盘选择，保持用户之前的选择
                        // 这里不需要做任何改变，因为上面已经初始化了空列表
                    }
                    
                    calculatorSelectedAmbers = amberMutableList
                }
                
                calculatorShowChefDialog = false
            },
            onClearCurrentChef = {
                // 清空当前选择框的厨师数据和心法盘选择，保留厨具和等级选择
                val mutableList = calculatorSelectedChefs.toMutableList()
                // 确保列表有足够的位置
                while (mutableList.size <= calculatorDialogIndex) {
                    mutableList.add(com.example.show_auto.data.Chef())
                }
                mutableList[calculatorDialogIndex] = com.example.show_auto.data.Chef() // 设置为空厨师
                calculatorSelectedChefs = mutableList
                
                // 清空对应的心法盘选择
                val amberMutableList = calculatorSelectedAmbers.toMutableList()
                while (amberMutableList.size <= calculatorDialogIndex) {
                    amberMutableList.add(emptyList())
                }
                amberMutableList[calculatorDialogIndex] = listOf(null, null, null)
                calculatorSelectedAmbers = amberMutableList
                
                // 注意：不清空厨具和等级选择，让用户保留这些配置
            },
            onDismiss = { calculatorShowChefDialog = false }
        )
    }
    
    if (calculatorShowEquipDialog) {
        CalculatorEquipSelectionDialog(
            equips = gameData?.equips ?: emptyList(),
            selectedEquips = calculatorSelectedEquips,
            dialogIndex = calculatorDialogIndex,
            skills = gameData?.skills ?: emptyList(),
            onEquipSelected = { equip ->
                val mutableList = calculatorSelectedEquips.toMutableList()
                // 确保列表有足够的位置
                while (mutableList.size <= calculatorDialogIndex) {
                    mutableList.add(com.example.show_auto.data.Equip())
                }
                mutableList[calculatorDialogIndex] = equip
                calculatorSelectedEquips = mutableList
                calculatorShowEquipDialog = false
            },
            onClearCurrentEquip = {
                val mutableList = calculatorSelectedEquips.toMutableList()
                // 确保列表有足够的位置
                while (mutableList.size <= calculatorDialogIndex) {
                    mutableList.add(com.example.show_auto.data.Equip())
                }
                mutableList[calculatorDialogIndex] = com.example.show_auto.data.Equip()
                calculatorSelectedEquips = mutableList
            },
            onDismiss = { calculatorShowEquipDialog = false }
        )
    }
    
    if (calculatorShowRecipeDialog) {
        // 计算当前选择槽位对应的厨师的增强技法值
        val chefIndex = calculatorDialogIndex / 3
        val currentChef = calculatorSelectedChefs.getOrNull(chefIndex)
        val currentEquip = calculatorSelectedEquips.getOrNull(chefIndex)
        val currentChefInteraction = chefInteractions.getOrNull(chefIndex)
        
        // 计算增强厨师（包含所有技法加成）
        val enhancedChef = if (currentChef != null) {
            com.example.show_auto.utils.ChefSkillCalculator.applyAllSkills(
                currentChef, ultimateSkills, currentEquip, gameData?.skills ?: emptyList(), currentChefInteraction
            )
        } else null
        
        CalculatorRecipeSelectionDialog(
            recipes = gameData?.recipes ?: emptyList(),
            selectedRecipes = calculatorSelectedRecipes,
            selectedChefs = calculatorSelectedChefs,
            selectedEquips = calculatorSelectedEquips,
            selectedRecipeSlotIndex = calculatorDialogIndex,
            skills = gameData?.skills ?: emptyList(),
            ultimateSkills = ultimateSkills,
            chefInteractions = chefInteractions,
            enhancedChef = enhancedChef, // 传递已经计算好的增强厨师
            onlyShowOwned = onlyShowOwnedRecipes,
            onOnlyShowOwnedChange = { 
                onlyShowOwnedRecipes = it
                settingsStorage.saveFilterOwnedRecipes(it)
            },
            settingsStorage = settingsStorage,
            gameData = gameData,
            chefAmbers = calculatorSelectedAmbers, // 厨师的心法盘配置列表
            chefLevels = calculatorSelectedLevels, // 厨师等级列表
            defaultMaxLevelAmber = defaultMaxLevelAmber, // 心法盘默认满级设置
            onRecipeSelected = { recipe ->
                val mutableList = calculatorSelectedRecipes.toMutableList()
                // 确保列表有足够的位置
                while (mutableList.size <= calculatorDialogIndex) {
                    mutableList.add(com.example.show_auto.data.Recipe())
                }
                mutableList[calculatorDialogIndex] = recipe
                calculatorSelectedRecipes = mutableList
                
                // 当手动选择菜谱时，更新该槽位的份数为计算结果中的份数
                val portionsMutableList = calculatorRecipePortions.toMutableList()
                while (portionsMutableList.size <= calculatorDialogIndex) {
                    portionsMutableList.add(0)
                }
                portionsMutableList[calculatorDialogIndex] = calculatorSelectedPortions
                calculatorRecipePortions = portionsMutableList
                
                System.out.println("手动选择菜谱 ${recipe.name} 到槽位 $calculatorDialogIndex，设置份数为: $calculatorSelectedPortions")
                calculatorShowRecipeDialog = false
            },
            onClearCurrentRecipe = {
                val mutableList = calculatorSelectedRecipes.toMutableList()
                // 确保列表有足够的位置
                while (mutableList.size <= calculatorDialogIndex) {
                    mutableList.add(com.example.show_auto.data.Recipe())
                }
                mutableList[calculatorDialogIndex] = com.example.show_auto.data.Recipe(name = "")
                calculatorSelectedRecipes = mutableList
                
                // 当清空菜谱时，重置该槽位的份数为0
                val portionsMutableList = calculatorRecipePortions.toMutableList()
                while (portionsMutableList.size <= calculatorDialogIndex) {
                    portionsMutableList.add(0)
                }
                portionsMutableList[calculatorDialogIndex] = 0
                calculatorRecipePortions = portionsMutableList
                
                System.out.println("清空槽位 $calculatorDialogIndex 的菜谱，重置份数为: 0")
            },
            onDismiss = { calculatorShowRecipeDialog = false }
        )
    }
    

} 

/**
 * 冲突菜谱弹窗组件
 */
@Composable
private fun ConflictRecipeDialog(
    recipe: Recipe,
    recipesByRune: Map<String, Pair<List<Recipe>, List<Recipe>>>,
    selectedRunes: Set<String>,
    guests: List<Guest>,
    globalConflictInfo: Pair<List<Recipe>, List<Recipe>>,
    onDismiss: () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text(
                text = "冲突菜谱",
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold
            )
        },
        text = {
            LazyColumn(
                modifier = Modifier.fillMaxWidth(),
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                // 基于全局冲突信息计算该菜谱的冲突情况
                val (_, globalConflictRecipes) = globalConflictInfo
                val conflictData = mutableMapOf<String, MutableList<Recipe>>()
                var totalConflictCount = 0
                
                // 找到与当前菜谱属于同一贵客的所有冲突菜谱（跨符文）
                guests.forEach { guest ->
                    // 检查该贵客是否对当前菜谱有选择
                    val hasCurrentRecipe = selectedRunes.any { runeName ->
                        guest.gifts.any { gift -> gift.recipe == recipe.name && gift.antique == runeName }
                    }
                    
                    if (hasCurrentRecipe) {
                        // 找到该贵客的所有冲突菜谱
                        globalConflictRecipes.forEach { conflictRecipe ->
                            selectedRunes.forEach { runeName ->
                                guest.gifts.forEach { gift ->
                                    if (gift.recipe == conflictRecipe.name && gift.antique == runeName) {
                                        conflictData.getOrPut(runeName) { mutableListOf() }.add(conflictRecipe)
                                        totalConflictCount++
                                    }
                                }
                            }
                        }
                    }
                }
                
                item {
                    Text(
                        text = "冲突菜谱 ($totalConflictCount)",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.error
                    )
                }
                
                conflictData.forEach { (runeName, recipes) ->
                    // 去重，因为可能有重复
                    val uniqueRecipes = recipes.distinctBy { it.name }
                    if (uniqueRecipes.isNotEmpty()) {
                        item {
                            Column {
                                Text(
                                    text = "$runeName (${uniqueRecipes.size})",
                                    fontSize = 14.sp,
                                    fontWeight = FontWeight.Medium,
                                    color = MaterialTheme.colorScheme.primary,
                                    modifier = Modifier.padding(start = 16.dp, top = 4.dp, bottom = 4.dp)
                                )
                                
                                uniqueRecipes.forEach { conflictRecipe ->
                                    RuneRecipeItem(
                                        recipe = conflictRecipe,
                                        guests = guests,
                                        modifier = Modifier.padding(top = 4.dp),
                                        isConflictTab = true,
                                        recipesByRune = recipesByRune,
                                        selectedRunes = selectedRunes,
                                        globalConflictInfo = globalConflictInfo,
                                        onShowConflict = null // 冲突弹窗中不显示"查看冲突"按钮
                                    )
                                }
                            }
                        }
                    }
                }
            }
        },
        confirmButton = {
            TextButton(onClick = onDismiss) {
                Text("关闭")
            }
        }
    )
} 

/**
 * 符文菜谱项组件
 * 专门用于符文查询页面的菜谱展示
 */
@Composable
private fun RuneRecipeItem(
    recipe: Recipe,
    guests: List<Guest>,
    modifier: Modifier = Modifier,
    isConflictTab: Boolean = false,
    recipesByRune: Map<String, Pair<List<Recipe>, List<Recipe>>> = emptyMap(),
    selectedRunes: Set<String> = emptySet(),
    globalConflictInfo: Pair<List<Recipe>, List<Recipe>> = Pair(emptyList(), emptyList()),
    onShowConflict: ((Recipe) -> Unit)? = null
) {
    Card(
        modifier = modifier
            .fillMaxWidth()
            .padding(horizontal = 4.dp, vertical = 6.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(20.dp)
        ) {
            // 第一行：菜谱名称（左对齐）+ 星级（贴近菜谱名）+ 时间（右对齐）
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 左侧：菜谱名称和星级
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.weight(1f)
                ) {
                    Text(
                        text = recipe.name,
                        fontSize = 14.sp,
                        fontWeight = FontWeight.Medium,
                        textAlign = TextAlign.Start
                    )
                    
                    Spacer(modifier = Modifier.width(8.dp))
                    
                    Text(
                        text = recipe.getRarityStars(),
                        fontSize = 12.sp,
                        color = MaterialTheme.colorScheme.primary,
                        fontWeight = FontWeight.Medium
                    )
                }
                
                // 右侧：制作时间（转换为分钟秒格式）
                val minutes = recipe.time / 60
                val seconds = recipe.time % 60
                val timeText = if (minutes > 0) {
                    "${minutes}分${seconds}秒"
                } else {
                    "${seconds}秒"
                }
                Text(
                    text = timeText,
                    fontSize = 12.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
            
            Spacer(modifier = Modifier.height(12.dp))
            
            // 第二行：开业贵客 + 查看冲突按钮
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 开业贵客（从游戏数据的guests数组中查找对应菜谱的贵客，格式：贵客名-符文名，多个贵客换行显示）
                val openingGuest = guests
                    .mapNotNull { guest -> 
                        guest.gifts.find { gift -> gift.recipe == recipe.name }?.let { gift ->
                            "${guest.name}-${gift.antique}"
                        }
                    }
                    .joinToString("\n")
                    .takeIf { it.isNotEmpty() } ?: ""
                
                Text(
                    text = openingGuest,
                    fontSize = 11.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    textAlign = TextAlign.Start,
                    modifier = Modifier.weight(1f)
                )
                
                // 查看冲突按钮（仅在无冲突标签页显示）
                if (!isConflictTab && onShowConflict != null) {
                    // 基于全局冲突检测：检查该菜谱是否有同贵客的其他菜谱在全局冲突列表中
                    val (_, globalConflictRecipes) = globalConflictInfo
                    
                    val hasRelatedConflicts = guests.any { guest ->
                        // 检查该贵客是否对当前菜谱有选择
                        val hasCurrentRecipe = selectedRunes.any { runeName ->
                            guest.gifts.any { gift -> gift.recipe == recipe.name && gift.antique == runeName }
                        }
                        
                        if (hasCurrentRecipe) {
                            // 检查该贵客是否有其他菜谱在全局冲突列表中
                            globalConflictRecipes.any { conflictRecipe ->
                                selectedRunes.any { runeName ->
                                    guest.gifts.any { gift -> gift.recipe == conflictRecipe.name && gift.antique == runeName }
                                }
                            }
                        } else {
                            false
                        }
                    }
                    
                    if (hasRelatedConflicts) {
                        OutlinedButton(
                            onClick = { onShowConflict(recipe) },
                            modifier = Modifier
                                .height(20.dp)
                                .padding(start = 8.dp),
                            colors = ButtonDefaults.outlinedButtonColors(
                                contentColor = MaterialTheme.colorScheme.primary
                            ),
                            border = BorderStroke(0.5.dp, MaterialTheme.colorScheme.primary),
                            shape = RoundedCornerShape(4.dp),
                            contentPadding = PaddingValues(horizontal = 6.dp, vertical = 0.dp)
                        ) {
                            Text(
                                text = "查看冲突",
                                fontSize = 8.sp,
                                fontWeight = FontWeight.Medium
                            )
                        }
                    }
                }
            }
            
            Spacer(modifier = Modifier.height(12.dp))
            
            // 第三行：来源（左对齐）+ 拥有状态（右对齐）
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 左侧：来源信息
                Text(
                    text = recipe.origin.replace("<br>", "、"),
                    fontSize = 11.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    textAlign = TextAlign.Start,
                    modifier = Modifier.weight(1f)
                )
                
                // 右侧：拥有状态
                Text(
                    text = if (recipe.got) "已拥有" else "未拥有",
                    fontSize = 10.sp,
                    color = if (recipe.got) 
                        MaterialTheme.colorScheme.primary 
                    else 
                        Color.Red,
                    fontWeight = if (recipe.got) FontWeight.Bold else FontWeight.Normal
                )
            }
        }
    }
}

/**
 * 菜谱项组件（完全复制自GuestQueryPage）
 */
@Composable
private fun RecipeItem(
    recipe: Recipe,
    selectedGuest: Guest?,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .fillMaxWidth()
            .padding(vertical = 2.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(12.dp)
        ) {
            Row(
                verticalAlignment = Alignment.Top
            ) {
                // 左侧：星级和菜谱名称
                Column(
                    modifier = Modifier.weight(1f)
                ) {
                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = recipe.getRarityStars(),
                            fontSize = 12.sp,
                            color = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.width(50.dp)
                        )

                        Text(
                            text = recipe.name,
                            fontSize = 14.sp,
                            fontWeight = FontWeight.Medium,
                            modifier = Modifier.weight(1f)
                        )

                        if (recipe.got) {
                            Icon(
                                imageVector = Icons.Default.Check,
                                contentDescription = "已拥有",
                                tint = MaterialTheme.colorScheme.primary,
                                modifier = Modifier.size(16.dp)
                            )
                        }
                    }
                }
            }
        }
    }

}

/**
 * 使用说明弹窗组件
 */
@Composable
private fun UsageGuideDialog(
    onDismiss: () -> Unit,
    tabIndex: Int,
    onTabChange: (Int) -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Column {
                Text(
                    text = "使用说明",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold
                )
                Spacer(modifier = Modifier.height(12.dp))
                
                // Tab切换区域
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(32.dp)
                        .background(
                            color = MaterialTheme.colorScheme.surfaceVariant,
                            shape = RoundedCornerShape(16.dp)
                        ),
                    horizontalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    // 贵客冲突查询标签
                    Surface(
                        onClick = { onTabChange(0) },
                        modifier = Modifier
                            .weight(1f)
                            .height(28.dp),
                        shape = RoundedCornerShape(14.dp),
                        color = if (tabIndex == 0) {
                            MaterialTheme.colorScheme.primary
                        } else {
                            Color.Transparent
                        }
                    ) {
                        Box(
                            modifier = Modifier.fillMaxSize(),
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = "贵客冲突查询",
                                fontSize = 12.sp,
                                fontWeight = FontWeight.Medium,
                                color = if (tabIndex == 0) {
                                    Color.White
                                } else {
                                    MaterialTheme.colorScheme.onSurfaceVariant
                                }
                            )
                        }
                    }
                    
                    // 贵客率计算器标签
                    Surface(
                        onClick = { onTabChange(1) },
                        modifier = Modifier
                            .weight(1f)
                            .height(28.dp),
                        shape = RoundedCornerShape(14.dp),
                        color = if (tabIndex == 1) {
                            MaterialTheme.colorScheme.primary
                        } else {
                            Color.Transparent
                        }
                    ) {
                        Box(
                            modifier = Modifier.fillMaxSize(),
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = "贵客率计算器",
                                fontSize = 12.sp,
                                fontWeight = FontWeight.Medium,
                                color = if (tabIndex == 1) {
                                    Color.White
                                } else {
                                    MaterialTheme.colorScheme.onSurfaceVariant
                                }
                            )
                        }
                    }
                }
            }
        },
        text = {
            when (tabIndex) {
                0 -> {
                    // 贵客冲突查询使用说明
                    LazyColumn(
                        modifier = Modifier.fillMaxWidth(),
                        verticalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        item {
                            Text(
                                text = "什么是贵客冲突？",
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Medium,
                                color = MaterialTheme.colorScheme.primary
                            )
                            Spacer(modifier = Modifier.height(4.dp))
                            Text(
                                text = "      开业时，如果制作的菜谱中有相同贵客，那么这些拥有相同贵客的菜谱就会产生冲突。由于贵客只能选择其中一个菜谱，导致其他菜谱贵客失效。",
                                fontSize = 14.sp,
                                lineHeight = 20.sp
                            )
                        }
                        
                        item {
                            Text(
                                text = "如何使用？",
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Medium,
                                color = MaterialTheme.colorScheme.primary
                            )
                            Spacer(modifier = Modifier.height(4.dp))
                            Text(
                                text = "1. 在搜索框中输入符文名称或点击分类按钮\n2. 选择要查询的符文（最多6个）\n3. 点击\"一键查询\"按钮，查看\"无冲突贵客菜谱\"和\"有冲突贵客菜谱\"\n4. 符文菜谱如有冲突，展示时间最短的菜谱为无冲突菜谱",
                                fontSize = 14.sp,
                                lineHeight = 20.sp
                            )
                        }
                        
                        item {
                            Text(
                                text = "冲突解决建议",
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Medium,
                                color = MaterialTheme.colorScheme.primary
                            )
                            Spacer(modifier = Modifier.height(4.dp))
                            Text(
                                text = "• 优先使用\"无冲突\"列表中的菜谱\n• 对于\"有冲突\"的菜谱，选择制作时间最短的菜谱\n• 点击\"查看冲突\"按钮可查看具体冲突详情\n• 合理搭配不同符文，避免过多冲突",
                                fontSize = 14.sp,
                                lineHeight = 20.sp
                            )
                        }
                    }
                }
                1 -> {
                    // 贵客率计算器使用说明
                    LazyColumn(
                        modifier = Modifier.fillMaxWidth(),
                        verticalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        item {
                            Text(
                                text = "什么是贵客率计算器？",
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Medium,
                                color = MaterialTheme.colorScheme.primary
                            )
                            Spacer(modifier = Modifier.height(4.dp))
                            Text(
                                text = "      贵客率计算器是一个符文菜谱配置辅助计算工具，可以计算不同厨师、厨具、菜谱组合下的贵客出现概率，帮助优化调整开业策略。",
                                fontSize = 14.sp,
                                lineHeight = 20.sp
                            )
                        }
                        
                        item {
                            Text(
                                text = "如何使用？",
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Medium,
                                color = MaterialTheme.colorScheme.primary
                            )
                            Spacer(modifier = Modifier.height(4.dp))
                            Text(
                                text = "1. 选择厨师：点击厨师选择框，选择要使用的厨师\n2. 选择厨具、心法盘：为每个厨师选择合适的厨具\n3. 在查询设置中勾选需要查询的符文，点击一键查询可自动推荐最优菜谱组合\n4. 也可以不配置厨师，直接在查询设置完成之后，直接点击一键查，自动推荐最优组合（ps：自动推荐不会考虑厨师技法值均衡分配）\n5. 查看结果：计算结果中会显示贵客出现概率和产出信息，场上也会展示推荐的菜谱",
                                fontSize = 14.sp,
                                lineHeight = 20.sp
                            )
                        }

                        item {
                            Text(
                                text = "查询设置介绍",
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Medium,
                                color = MaterialTheme.colorScheme.primary
                            )
                            Spacer(modifier = Modifier.height(4.dp))
                            Text(
                                text = "1. 心法盘默认满级：开启后给厨师设置满级满朋陨\n2. 默认全修炼：所有厨师修炼技能默认生效\n3. 启用厨具遗玉：开启后使用厨师自身佩戴的厨具和遗玉，关闭则不使用任何厨具遗玉（可手动配置厨具｜遗玉）\n4. 使用全部厨师：一键查询中会使用全部厨师（包括未拥有）的厨师进行计算\n5. 制作时间：一键查询中菜谱分配的总时间上限\n6. 查询必来：不考虑最高效率，使用高贵客高暴击的厨师进行计算n7. 查询效率：考虑刺客厨师，并且默认使用各星级菜谱保底份数进行查询",
                                fontSize = 14.sp,
                                lineHeight = 20.sp
                            )
                        }
                          
                        item {
                            Text(
                                text = "使用建议",
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Medium,
                                color = MaterialTheme.colorScheme.primary
                            )
                            Spacer(modifier = Modifier.height(4.dp))
                            Text(
                                text = "• 可先使用一键查询查询效率最高组合，然后手动调整组合、厨具、心法盘，再设置查询符文进行一键查询\n• \n• 如果想要查询自身最佳搭配建议开启启用厨具遗玉，保证使用个人厨师数据\n• 根据目标符文技法值要求调整厨师组合，推荐的组合只能保证效率最高，不能保证技法平衡\n• 贵客率较低的情况下建议使用查询效率模式，7份菜谱碰瓷符文效率最高（就是费肝～）",
                                fontSize = 14.sp,
                                lineHeight = 20.sp
                            )
                        }
                    }
                }
            }
        },
        confirmButton = {
            TextButton(onClick = onDismiss) {
                Text("知道了")
            }
        }
    )
}

/**
 * 贵客率计算器专用厨师选择框
 */
@Composable
private fun CalculatorChefBox(
    chef: com.example.show_auto.data.Chef?,
    equip: com.example.show_auto.data.Equip?,
    skills: List<com.example.show_auto.data.Skill>,
    ultimateSkills: UltimateSkillsState,
    chefInteractionBonus: Map<String, Int>? = null,
    gameData: com.example.show_auto.data.GameData? = null,
    personalData: com.example.show_auto.data.PersonalData? = null,
    columnIndex: Int = -1, // 添加列索引参数
    calculatorSelectedLevels: List<Int?> = emptyList(), // 添加等级选择数据
    calculatorSelectedAmbers: List<List<com.example.show_auto.data.Amber?>> = emptyList(), // 添加心法盘选择数据
    calculatorSelectedChefs: List<com.example.show_auto.data.Chef> = emptyList(), // 添加已选择厨师列表
    viewModel: MainViewModel,
    currentDefaultAllUltimate: Boolean = false, // 添加默认全修炼参数
    usePersonalData: Boolean = true, // 添加使用个人数据参数
    defaultMaxLevelAmber: Boolean = false, // 添加心法盘默认满级参数
    onClick: () -> Unit,
    onAmberButtonClick: () -> Unit, // 添加心法盘按钮点击回调
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .aspectRatio(1f) // 保持正方形比例
            .clickable { onClick() },
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surface
        ),
        border = BorderStroke(
            width = 1.dp,
            color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f)
        )
    ) {
        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            if (chef != null && chef.name.isNotEmpty()) {
                // 显示厨师详细信息
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(4.dp),
                    verticalArrangement = Arrangement.spacedBy(0.5.dp)
                ) {
                    // 第一行：厨师名称 + 星级
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = chef.name,
                            fontSize = 10.sp,
                            fontWeight = FontWeight.Bold,
                            color = MaterialTheme.colorScheme.primary,
                            maxLines = 1
                        )

                        Spacer(modifier = Modifier.width(4.dp))

                        // 星级显示
                        repeat(chef.rarity) {
                            Icon(
                                imageVector = Icons.Default.Star,
                                contentDescription = null,
                                tint = MaterialTheme.colorScheme.primary,
                                modifier = Modifier.size(6.dp)
                            )
                        }
                    }
                    
                    // 第二行：贵客率和开业时间显示
                    val currentPersonalData = viewModel.personalData.collectAsState().value
                    
                    // 使用 remember 确保当 equip 改变时重新计算
                    val totalGuestRate = remember(equip, columnIndex, calculatorSelectedLevels, calculatorSelectedAmbers, calculatorSelectedChefs, currentDefaultAllUltimate, usePersonalData) {
                        if (columnIndex >= 0) {
                            // 使用计算器中选择的数据，并考虑场上性别技能影响
                            if (usePersonalData) {
                                val selectedLevel = calculatorSelectedLevels.getOrNull(columnIndex)
                                val selectedAmbers = calculatorSelectedAmbers.getOrNull(columnIndex)
                                // 获取其他已选择的厨师列表（排除当前厨师）
                                val otherSelectedChefs = calculatorSelectedChefs.filterIndexed { index, otherChef -> 
                                    index != columnIndex && otherChef.name.isNotEmpty() 
                                }
                                calculateGuestRateWithFieldGenderBonus(chef, skills, gameData, currentPersonalData, selectedLevel, selectedAmbers, equip, otherSelectedChefs, currentDefaultAllUltimate)
                            } else {
                                // 当"启用厨具遗玉"关闭时，不使用个人数据中的厨具和心法盘，但使用手动选择的厨具和心法盘
                                val selectedLevel = calculatorSelectedLevels.getOrNull(columnIndex)
                                var selectedAmbers = calculatorSelectedAmbers.getOrNull(columnIndex)
                                
                                // 如果开启了心法盘默认满级，即使"启用厨具遗玉"关闭，也要使用满朋陨进行计算
                                if (defaultMaxLevelAmber && gameData != null && selectedAmbers != null) {
                                    // 检查是否有空的心法盘位置（表示需要填充满朋陨）
                                    val hasEmptyAmberPositions = selectedAmbers.any { it == null }
                                    if (hasEmptyAmberPositions) {
                                        // 创建新的心法盘列表，对空位置填充满朋陨
                                        val enhancedAmbers = selectedAmbers.toMutableList()
                                        applyMaxLevelAmberToBluePositions(chef, enhancedAmbers, gameData, true)
                                        selectedAmbers = enhancedAmbers
                                    }
                                }
                                
                                // 获取其他已选择厨师列表（排除当前厨师）
                                val otherSelectedChefs = calculatorSelectedChefs.filterIndexed { index, otherChef -> 
                                    index != columnIndex && otherChef.name.isNotEmpty() 
                                }
                                calculateGuestRateWithFieldGenderBonus(chef, skills, gameData, null, selectedLevel, selectedAmbers, equip, otherSelectedChefs, currentDefaultAllUltimate)
                            }
                        } else {
                            // 启用厨具遗玉
                            if (usePersonalData) {
                                calculateTotalGuestRateBonusWithEquip(chef, equip, skills, gameData, currentPersonalData, currentDefaultAllUltimate)
                            } else {
                                // 当"启用厨具遗玉"关闭时，不使用个人数据中的厨具和心法盘，但使用手动选择的厨具
                                calculateTotalGuestRateBonusWithEquip(chef, equip, skills, gameData, null, currentDefaultAllUltimate)
                            }
                        }
                    }
                    
                    val openingTimeBonus = remember(equip, currentDefaultAllUltimate, usePersonalData) {
                        if (usePersonalData) {
                            calculateOpeningTimeBonus(chef, equip, skills, gameData, currentPersonalData, currentDefaultAllUltimate)
                        } else {
                            // 当"启用厨具遗玉"关闭时，不使用个人数据中的厨具和心法盘，但使用手动选择的厨具
                            calculateOpeningTimeBonus(chef, equip, skills, gameData, null, currentDefaultAllUltimate)
                        }
                    }
                    
                    // 检查是否有三个属性
                    val hasCritSkill = if (usePersonalData) {
                        hasCritSkillWithEquip(chef, equip, skills, currentDefaultAllUltimate)
                    } else {
                        // 当"启用厨具遗玉"关闭时，不使用个人数据中的厨具和心法盘，但使用手动选择的厨具
                        hasCritSkillWithEquip(chef, equip, skills, currentDefaultAllUltimate)
                    }
                    val hasTimeSkill = openingTimeBonus != 0.0
                    val hasThreeAttributes = totalGuestRate > 0 && hasCritSkill && hasTimeSkill
                    
                    // 提前计算暴击率加成，避免作用域问题
                    val critRateBonus = remember(equip, columnIndex, calculatorSelectedLevels, calculatorSelectedAmbers, currentDefaultAllUltimate, usePersonalData) {
                        if (columnIndex >= 0) {
                            if (usePersonalData) {
                                val selectedLevel = calculatorSelectedLevels.getOrNull(columnIndex)
                                val selectedAmbers = calculatorSelectedAmbers.getOrNull(columnIndex)
                                calculateTotalCritRateBonusWithCalculatorData(chef, skills, gameData, currentPersonalData, selectedLevel, selectedAmbers, equip)
                            } else {
                                // 当"启用厨具遗玉"关闭时，不使用个人数据中的厨具和心法盘，但使用手动选择的厨具和心法盘
                                val selectedLevel = calculatorSelectedLevels.getOrNull(columnIndex)
                                var selectedAmbers = calculatorSelectedAmbers.getOrNull(columnIndex)
                                
                                // 如果开启了心法盘默认满级，即使"启用厨具遗玉"关闭，也要使用满朋陨进行计算
                                if (defaultMaxLevelAmber && gameData != null && selectedAmbers != null) {
                                    // 检查是否有空的心法盘位置（表示需要填充满朋陨）
                                    val hasEmptyAmberPositions = selectedAmbers.any { it == null }
                                    if (hasEmptyAmberPositions) {
                                        // 创建新的心法盘列表，对空位置填充满朋陨
                                        val enhancedAmbers = selectedAmbers.toMutableList()
                                        applyMaxLevelAmberToBluePositions(chef, enhancedAmbers, gameData, true)
                                        selectedAmbers = enhancedAmbers
                                    }
                                }
                                
                                calculateTotalCritRateBonusWithCalculatorData(chef, skills, gameData, null, selectedLevel, selectedAmbers, equip)
                            }
                        } else {
                            if (usePersonalData) {
                                calculateTotalCritRateBonusWithEquip(chef, equip, skills, gameData, currentPersonalData)
                            } else {
                                // 当"启用厨具遗玉"关闭时，不使用个人数据中的厨具和心法盘，但使用手动选择的厨具
                                calculateTotalCritRateBonusWithEquip(chef, equip, skills, gameData, null)
                            }
                        }
                    }
                    
                    if (hasThreeAttributes) {
                        // 三个属性都有时，使用紧凑格式
                        val combinedStatsText = buildString {
                            // 贵客率
                            append("贵+${formatPercentage(totalGuestRate)}%")
                            
                            // 暴击率
                            append("爆")
                            when {
                                critRateBonus > 0 -> append("+${formatPercentage(critRateBonus)}%")
                                critRateBonus == 0.0 -> append("+0%")
                                else -> append("${formatPercentage(critRateBonus)}%")
                            }
                            
                            // 时间
                            append("时")
                            when {
                                openingTimeBonus > 0 -> append("+${formatPercentage(openingTimeBonus)}%")
                                else -> append("${formatPercentage(openingTimeBonus)}%")
                            }
                        }
                        
                        // 使用带颜色的文本显示
                        val annotatedText = buildAnnotatedString {
                            // 贵客率部分
                            val guestRateEnd = combinedStatsText.indexOf("爆")
                            withStyle(style = SpanStyle(
                                color = Color(0xFF7B1FA2),
                                fontWeight = FontWeight.Medium
                            )) {
                                append(combinedStatsText.substring(0, guestRateEnd))
                            }
                            
                            // 暴击率部分
                            val critStart = guestRateEnd
                            val critEnd = combinedStatsText.indexOf("时")
                            withStyle(style = SpanStyle(
                                color = when {
                                    critRateBonus > 0 -> Color(0xFFF44336) // 橙色
                                    critRateBonus == 0.0 -> Color(0xFF9E9E9E) // 灰色
                                    else -> Color(0xFFF44336) // 红色
                                },
                                fontWeight = FontWeight.Medium
                            )) {
                                append(combinedStatsText.substring(critStart, critEnd))
                            }
                            
                            // 时间部分
                            withStyle(style = SpanStyle(
                                color = if (openingTimeBonus > 0) Color(0xFFF44336) else Color(0xFF4CAF50),
                                fontWeight = FontWeight.Medium
                            )) {
                                append(combinedStatsText.substring(critEnd))
                            }
                        }
                        
                        Text(
                            text = annotatedText,
                            fontSize = 7.sp, // 调小文字大小
                            modifier = Modifier.fillMaxWidth()
                        )
                    } else {
                        // 少于三个属性时，使用原来的格式
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.spacedBy(2.dp)
                        ) {
                            // 贵客率显示
                            Text(
                                text = if (totalGuestRate > 0) "贵客+${formatPercentage(totalGuestRate)}%" else "贵客+0%",
                                fontSize = 8.sp,
                                color = if (totalGuestRate > 0) Color(0xFF7B1FA2) else MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f),
                                fontWeight = if (totalGuestRate > 0) FontWeight.Medium else FontWeight.Normal
                            )
                            
                            // 暴击率显示（当有暴击技能时显示）
                            if (hasCritSkill) {
                                val critRateBonus = remember(equip, columnIndex, calculatorSelectedLevels, calculatorSelectedAmbers, currentDefaultAllUltimate) {
                                    if (columnIndex >= 0) {
                                        val selectedLevel = calculatorSelectedLevels.getOrNull(columnIndex)
                                        val selectedAmbers = calculatorSelectedAmbers.getOrNull(columnIndex)
                                        calculateTotalCritRateBonusWithCalculatorData(chef, skills, gameData, currentPersonalData, selectedLevel, selectedAmbers, equip)
                                    } else {
                                        calculateTotalCritRateBonusWithEquip(chef, equip, skills, gameData, currentPersonalData)
                                    }
                                }
                                
                                val critRateText = when {
                                    critRateBonus > 0 -> "暴击+${formatPercentage(critRateBonus)}%"
                                    critRateBonus == 0.0 -> "暴击+0%"
                                    else -> "暴击${formatPercentage(critRateBonus)}%"
                                }
                                
                                Text(
                                    text = critRateText,
                                    fontSize = 8.sp,
                                    color = when {
                                        critRateBonus > 0 -> Color(0xFFF44336) // 橙色
                                        critRateBonus == 0.0 -> Color(0xFF9E9E9E) // 灰色
                                        else -> Color(0xFFF44336) // 红色
                                    },
                                    fontWeight = FontWeight.Medium
                                )
                            }
                            
                            // 时间显示（当有开业时间加成时显示，即使没有贵客率也要显示）
                            if (hasTimeSkill) {
                                val openingTimeText = when {
                                    openingTimeBonus > 0 -> "时间+${formatPercentage(openingTimeBonus)}%"
                                    else -> "时间${formatPercentage(openingTimeBonus)}%"
                                }
                                val openingTimeColor = if (openingTimeBonus > 0) {
                                    Color(0xFFF44336) // 红色，表示增加时间（不利）
                                } else {
                                    Color(0xFF4CAF50) // 绿色，表示减少时间（有利）
                                }
                                
                                Text(
                                    text = openingTimeText,
                                    fontSize = 8.sp,
                                    color = openingTimeColor,
                                    fontWeight = FontWeight.Medium
                                )
                            }
                        }
                    }
                    
                    // 第三行：技法数值按降序排列显示（使用带颜色的文本格式）
                    val enhancedChef = ChefSkillCalculator.applyAllSkills(chef, ultimateSkills, equip, skills, chefInteractionBonus)
                    
                    // 计算受心法盘影响的技法值
                    val techniqueValuesWithAmbers = if (columnIndex >= 0) {
                        val selectedLevel = calculatorSelectedLevels.getOrNull(columnIndex)
                        val selectedAmbers = calculatorSelectedAmbers.getOrNull(columnIndex)
                        calculateTechniqueValuesWithAmbers(chef, skills, gameData, selectedLevel, selectedAmbers, enhancedChef)
                    } else {
                        emptyMap()
                    }
                    
                    val skillValues = listOf(
                        Triple("炒", enhancedChef.stirfry, "stirfry"),
                        Triple("煮", enhancedChef.boil, "boil"),
                        Triple("切", enhancedChef.knife, "knife"),
                        Triple("炸", enhancedChef.fry, "fry"),
                        Triple("烤", enhancedChef.bake, "bake"),
                        Triple("蒸", enhancedChef.steam, "steam")
                    ).map { (skillName, skillValue, skillType) ->
                        // 如果有心法盘影响，使用心法盘计算的值
                        val finalValue = if (columnIndex >= 0) {
                            val amberValue = techniqueValuesWithAmbers[skillType]?.second ?: skillValue
                            amberValue
                        } else {
                            skillValue
                        }
                        Triple(skillName, finalValue, skillType)
                    }.sortedByDescending { it.second }
                    
                    // 构建带颜色的技法文本
                    val skillAnnotatedText = buildAnnotatedString {
                        // 第一行：前三个技法
                        skillValues.take(3).forEachIndexed { index, (skillName, skillValue, skillType) ->
                            val skillColor = when {
                                // 心法盘影响（红色）
                                columnIndex >= 0 && techniqueValuesWithAmbers[skillType]?.first != techniqueValuesWithAmbers[skillType]?.second ->
                                    Color(0xFFF44336) // 红色：心法盘影响
                                ChefSkillCalculator.hasSpecificChefInteractionBonus(chefInteractionBonus, skillType) &&
                                ChefSkillCalculator.hasSpecificEquipSkillBonus(chef, equip, skills, skillType) ->
                                    Color(0xFF9C27B0) // 紫色：同时有厨师间技法影响和厨具技能加成
                                ChefSkillCalculator.hasSpecificChefInteractionBonus(chefInteractionBonus, skillType) ->
                                    MaterialTheme.colorScheme.primary // 蓝色：厨师间技法影响
                                ChefSkillCalculator.hasSpecificEquipSkillBonus(chef, equip, skills, skillType) ->
                                    Color(0xFF4CAF50) // 绿色：厨具技能加成
                                else -> MaterialTheme.colorScheme.onSurfaceVariant // 正常颜色：包括个人技法加成
                            }
                            
                            withStyle(style = SpanStyle(color = skillColor)) {
                                append("${skillName}${skillValue}")
                            }
                            
                            if (index < 2) {
                                append(" ")
                            }
                        }
                        
                        append("\n")
                        
                        // 第二行：后三个技法
                        skillValues.drop(3).forEachIndexed { index, (skillName, skillValue, skillType) ->
                            val skillColor = when {
                                // 心法盘影响（红色）
                                columnIndex >= 0 && techniqueValuesWithAmbers[skillType]?.first != techniqueValuesWithAmbers[skillType]?.second ->
                                    Color(0xFFF44336) // 红色：心法盘影响
                                ChefSkillCalculator.hasSpecificChefInteractionBonus(chefInteractionBonus, skillType) &&
                                ChefSkillCalculator.hasSpecificEquipSkillBonus(chef, equip, skills, skillType) ->
                                    Color(0xFF9C27B0) // 紫色：同时有厨师间技法影响和厨具技能加成
                                ChefSkillCalculator.hasSpecificChefInteractionBonus(chefInteractionBonus, skillType) ->
                                    MaterialTheme.colorScheme.primary // 蓝色：厨师间技法影响
                                ChefSkillCalculator.hasSpecificEquipSkillBonus(chef, equip, skills, skillType) ->
                                    Color(0xFF4CAF50) // 绿色：厨具技能加成
                                else -> MaterialTheme.colorScheme.onSurfaceVariant // 正常颜色：包括个人技法加成
                            }
                            
                            withStyle(style = SpanStyle(color = skillColor)) {
                                append("${skillName}${skillValue}")
                            }
                            
                            if (index < 2) {
                                append(" ")
                            }
                        }
                    }
                    
                    Text(
                        text = skillAnnotatedText,
                        fontSize = 8.sp,
                        maxLines = 2, // 允许最多2行显示
                        lineHeight = 10.sp,
                        modifier = Modifier
                            .fillMaxWidth()
                            .heightIn(min = 10.dp, max = 30.dp) // 增加高度限制，确保第二行文字不被遮挡
                    )

                    // 第四行：心法盘按钮（左侧居中）+ 状态信息（右侧）
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        // 左侧区域：心法盘按钮居中
                        Box(
                            modifier = Modifier
                                .weight(1f)
                                .padding(top = 2.dp), // 向下移动一点
                            contentAlignment = Alignment.Center
                        ) {
                            Button(
                                onClick = onAmberButtonClick,
                                modifier = Modifier
                                    .height(20.dp)
                                    .width(60.dp), // 固定宽度，缩小按钮
                                colors = ButtonDefaults.buttonColors(
                                    containerColor = MaterialTheme.colorScheme.surface,
                                    contentColor = MaterialTheme.colorScheme.onSurface
                                ),
                                contentPadding = PaddingValues(0.dp),
                                border = BorderStroke(
                                    width = 1.dp,
                                    color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f)
                                )
                            ) {
                                Box(
                                    modifier = Modifier.fillMaxSize(),
                                    contentAlignment = Alignment.Center
                                ) {
                                    Text(
                                        text = "心法盘",
                                        fontSize = 7.sp,
                                        fontWeight = FontWeight.Medium,
                                        textAlign = TextAlign.Center
                                    )
                                }
                            }
                        }

                        // 右侧区域：拥有状态和修炼状态显示
                        Text(
                            text = buildAnnotatedString {
                                // 拥有状态
                                withStyle(
                                    style = SpanStyle(
                                        color = if (chef.got) MaterialTheme.colorScheme.primary else Color.Red,
                                        fontWeight = if (chef.got) FontWeight.Bold else FontWeight.Normal
                                    )
                                ) {
                                    append(if (chef.got) "已拥有" else "未拥有")
                                }
                                
                                // 只有已拥有时才显示修炼状态
                                if (chef.got) {
                                    append("\n")
                                    // 修炼状态
                                    withStyle(
                                        style = SpanStyle(
                                            color = if (chef.ult) MaterialTheme.colorScheme.primary else Color.Red,
                                            fontWeight = if (chef.ult) FontWeight.Bold else FontWeight.Normal
                                        )
                                    ) {
                                        append(if (chef.ult) "已修炼" else "未修炼")
                                    }
                                }
                            },
                            fontSize = 8.sp,
                            lineHeight = 9.sp,
                            textAlign = TextAlign.End
                        )
                    }
                }
            } else {
                // 厨师占位符
                Text(
                    text = "+ 厨师",
                    fontSize = 10.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
    }
}

/**
 * 贵客率计算器专用厨具选择框
 */
@Composable
private fun CalculatorEquipBox(
    equip: com.example.show_auto.data.Equip?,
    skills: List<com.example.show_auto.data.Skill>,
    allRecipes: List<com.example.show_auto.data.Recipe>,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .height(30.dp) // 调小高度为30
            .clickable { onClick() },
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surface
        ),
        border = BorderStroke(
            width = 1.dp,
            color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f)
        )
    ) {
        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            if (equip != null && equip.name.isNotEmpty()) {
                // 只显示厨具名称，居中显示
                Text(
                    text = equip.name,
                    fontSize = 11.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.primary,
                    maxLines = 1,
                    textAlign = TextAlign.Center,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 2.dp) // 减小上下边距
                )
            } else {
                // 厨具占位符
                Text(
                    text = "+ 厨具",
                    fontSize = 10.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    textAlign = TextAlign.Center,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 2.dp) // 减小上下边距
                )
            }
        }
    }
}

/**
 * 贵客率计算器专用菜谱选择框
 */
@Composable
private fun CalculatorRecipeBox(
    recipe: com.example.show_auto.data.Recipe?,
    chef: com.example.show_auto.data.Chef?,
    equip: com.example.show_auto.data.Equip?,
    skills: List<com.example.show_auto.data.Skill>,
    ultimateSkills: com.example.show_auto.ui.pages.UltimateSkillsState,
    recipeLimits: com.example.show_auto.ui.pages.RecipeLimitsState,
    chefInteractionBonus: Map<String, Int>? = null,
    actualPortions: Int? = null, // 一键查询的实际分配份数
    gameData: com.example.show_auto.data.GameData? = null,
    chefIndex: Int = -1, // 厨师在列表中的索引
    chefAmbers: List<com.example.show_auto.data.Amber?> = listOf(null, null, null), // 厨师的心法盘配置
    chefLevel: Int = 1, // 厨师等级
    defaultMaxLevelAmber: Boolean = false, // 心法盘默认满级设置
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .fillMaxWidth()
            .height(DeviceCompatibility.getAdaptiveHeight(85.dp)) // 增加高度以完整显示三行内容
            .clickable { onClick() },
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surface
        ),
        border = BorderStroke(
            width = 1.dp,
            color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f)
        )
    ) {
        if (recipe != null && recipe.name.isNotEmpty()) {
            // 显示菜谱信息
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(6.dp),
                verticalArrangement = Arrangement.spacedBy(0.dp)
            ) {
                // 第一行：菜谱名（左对齐）+ 品级
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
            ) {
                // 判断是否为双贵客菜谱
                val guestCount = remember(recipe.name, gameData) {
                    gameData?.guests?.count { guest ->
                        guest.gifts.any { gift -> 
                            gift.recipe == recipe.name 
                        }
                    } ?: 1
                }
                val isDualGuestRecipe = guestCount >= 2
                
                Text(
                    text = recipe.name,
                    fontSize = 9.sp,
                    fontWeight = if (isDualGuestRecipe) FontWeight.ExtraBold else FontWeight.Bold,
                    color = if (isDualGuestRecipe) Color.Red else MaterialTheme.colorScheme.secondary,
                        maxLines = 1,
                        modifier = Modifier.weight(1f)
                    )

                    // 品级显示（如果有厨师）
                    if (chef != null) {
                        val enhancedChef = com.example.show_auto.utils.ChefSkillCalculator.applyAllSkills(
                            chef, ultimateSkills, equip, skills, chefInteractionBonus
                        )
                        
                        // 如果启用厨具遗玉，还需要应用心法盘技法值加成
                        val finalEnhancedChef = if (gameData != null && chefIndex >= 0) {
                            // 使用传入的心法盘配置和等级
                            val finalAmbers = if (defaultMaxLevelAmber) {
                                applyMaxLevelAmberToBluePositions(chef, chefAmbers.toMutableList(), gameData, true)
                            } else {
                                chefAmbers
                            }
                            
                            // 计算心法盘技法值加成
                            val techniqueValuesWithAmbers = calculateTechniqueValuesWithAmbers(chef, skills, gameData, chefLevel, finalAmbers, enhancedChef)
                            
                            // 创建包含心法盘加成的最终厨师数据
                            enhancedChef.copy(
                                stirfry = techniqueValuesWithAmbers["stirfry"]?.second ?: enhancedChef.stirfry,
                                boil = techniqueValuesWithAmbers["boil"]?.second ?: enhancedChef.boil,
                                knife = techniqueValuesWithAmbers["knife"]?.second ?: enhancedChef.knife,
                                fry = techniqueValuesWithAmbers["fry"]?.second ?: enhancedChef.fry,
                                bake = techniqueValuesWithAmbers["bake"]?.second ?: enhancedChef.bake,
                                steam = techniqueValuesWithAmbers["steam"]?.second ?: enhancedChef.steam
                            )
                        } else {
                            enhancedChef
                        }
                        
                        val rank = com.example.show_auto.utils.RecipeRankCalculator.calculateRecipeRank(finalEnhancedChef, recipe)
                        val rankText = com.example.show_auto.utils.RecipeRankCalculator.getRankShortText(rank)
                        val rankColor = com.example.show_auto.utils.RecipeRankCalculator.getRankColor(rank)

                Text(
                            text = rankText,
                            fontSize = 10.sp,
                            color = Color(rankColor),
                            fontWeight = FontWeight.Bold
                        )
                        
                        Spacer(modifier = Modifier.width(2.dp)) // 缩短间隔
                        
                        // 计算并显示最大制作份数
                        val basePortions = when (recipe.rarity) {
                            1 -> 40  // 1星菜谱基础份数
                            2 -> 30  // 2星菜谱基础份数
                            3 -> 25  // 3星菜谱基础份数
                            4 -> 20  // 4星菜谱基础份数
                            5 -> 15  // 5星菜谱基础份数
                            else -> 0 // 默认份数
                        }
                        
                        val limitBonus = when (recipe.rarity) {
                            1 -> recipeLimits.star1
                            2 -> recipeLimits.star2
                            3 -> recipeLimits.star3
                            4 -> recipeLimits.star4
                            5 -> recipeLimits.star5
                            else -> 0
                        }
                        
                        val maxPortions = basePortions + limitBonus
                        
                        // 如果有一键查询的实际分配份数，显示实际份数；否则显示0份（没有菜谱时）
                        val displayPortions = actualPortions ?: 0
                        
                        Text(
                            text = "${displayPortions}份",
                    fontSize = 8.sp,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            fontWeight = FontWeight.Normal
                        )
                    }
                }



                // 第二行：星级+符文简写（左对齐）+ 技法（右对齐）
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    // 星级显示（左对齐）
                    val starText = when (recipe.rarity) {
                        1 -> "一🔥"
                        2 -> "二🔥"
                        3 -> "三🔥"
                        4 -> "四🔥"
                        5 -> "五🔥"
                        else -> "${recipe.rarity}🔥"
                    }
                    Text(
                        text = starText,
                        fontSize = 8.sp, // 调小星级文字
                        color = MaterialTheme.colorScheme.primary,
                        fontWeight = FontWeight.Medium
                    )
                    
                    // 符文名称简写
                    val runeName = remember(recipe.name, gameData) {
                        gameData?.guests?.flatMap { guest ->
                            guest.gifts?.filter { gift ->
                                gift.recipe == recipe.name
                            }?.map { gift ->
                                gift.antique
                            } ?: emptyList()
                        }?.firstOrNull() ?: ""
                    }
                    
                    if (runeName.isNotEmpty()) {
                        Spacer(modifier = Modifier.width(4.dp))
                        // 将符文名称转换为简写
                        val runeShortName = when (runeName) {
                            "五星炒果" -> "炒果"
                            "香烤鱼排" -> "鱼排"
                            "千年煮鳖" -> "煮鳖"
                            "蒸馏杯" -> "蒸馏"
                            "恐怖利刃" -> "恐怖"
                            "鼓风机" -> "鼓风"
                            "刀嘴鹦鹉" -> "鹦鹉"
                            "一昧真火" -> "一昧"
                            "耐煮的水草" -> "水草"
                            "剪刀蟹" -> "剪刀"
                            "油火虫" -> "火虫"
                            "蒸汽耳环" -> "蒸汽"
                            "防水的柠檬" -> "柠檬"
                            "烤焦的菊花" -> "菊花"
                            "五香果" -> "五香"
                            else -> if (runeName.length >= 2) runeName.take(2) else runeName // 其他符文取前两个字符，避免空安全问题
                        }
                        Text(
                            text = runeShortName,
                            fontSize = 8.sp, // 调小符文简写文字
                            color = MaterialTheme.colorScheme.tertiary,
                            fontWeight = FontWeight.Normal
                        )
                    }

                    Spacer(modifier = Modifier.weight(1f))

                    // 技法值（右对齐）- 始终显示菜谱技法需求，不计算神差值
                    Text(
                        text = getRecipeSkillText(recipe).ifEmpty { "无技法" },
                        fontSize = 8.sp, // 调小技法值文字
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        maxLines = 1
                    )
                }
                
                // 第三行：单份制作时间（左对齐）+ 拥有状态（右对齐）
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    // 单份制作时间（左对齐）
                    val cookingTime = recipe.time
                    val minutes = cookingTime / 60
                    val seconds = cookingTime % 60
                    val timeText = if (minutes > 0) {
                        "${minutes}分${seconds}秒"
                    } else {
                        "${seconds}秒"
                    }
                    
                    Text(
                        text = timeText,
                        fontSize = 8.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        maxLines = 1,
                        modifier = Modifier.weight(1f)
                    )

                    // 拥有状态（右对齐）
                    Text(
                        text = if (recipe.got) "已拥有" else "未拥有",
                        fontSize = 9.sp,
                        color = if (recipe.got) {
                            MaterialTheme.colorScheme.primary
                        } else {
                            Color.Red
                        },
                        fontWeight = if (recipe.got) FontWeight.Bold else FontWeight.Normal
                    )
                }
            }
        } else {
            // 空状态
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = "+ 菜谱",
                    fontSize = 10.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
    }
}

/**
 * 贵客率计算器专用厨师选择对话框
 */
@Composable
private fun CalculatorChefSelectionDialog(
    chefs: List<com.example.show_auto.data.Chef>,
    selectedChefs: List<com.example.show_auto.data.Chef>,
    skills: List<com.example.show_auto.data.Skill>,
    gameData: com.example.show_auto.data.GameData?,
    personalData: com.example.show_auto.data.PersonalData?,
    dialogIndex: Int,
    defaultMaxLevelAmber: Boolean,
    onChefSelected: (com.example.show_auto.data.Chef) -> Unit,
    onClearCurrentChef: () -> Unit,
    onDismiss: () -> Unit
) {
    val context = LocalContext.current
    val settingsStorage = remember { com.example.show_auto.data.SettingsStorage(context) }
    
    var searchText by remember { mutableStateOf("") }
    
    // 从持久化存储加载筛选按钮状态，默认显示已有厨师，默认过滤贵客厨师
    var onlyShowOwned by remember { mutableStateOf(settingsStorage.getCalculatorOnlyShowOwned()) }
    var onlyShowAuraChefs by remember { mutableStateOf(true) } // 默认开启贵客厨师过滤
    var onlyShowUltimateChefs by remember { mutableStateOf(settingsStorage.getCalculatorOnlyShowUltimateChefs()) }
    var onlyShowCritChefs by remember { mutableStateOf(false) } // 查询暴击厨师状态
    var onlyShowAssassinChefs by remember { mutableStateOf(settingsStorage.getCalculatorOnlyShowAssassinChefs()) }
    
    // 实时读取心法盘默认满级设置状态，确保开关变化时立即生效
    var currentMaxLevelAmber by remember { mutableStateOf(defaultMaxLevelAmber) }
    // 实时读取默认全修炼设置状态
    var currentDefaultAllUltimate by remember { mutableStateOf(settingsStorage.getCalculatorDefaultAllUltimate()) }
    // 实时读取使用个人数据设置状态
    var usePersonalData by remember { mutableStateOf(settingsStorage.getCalculatorUsePersonalData()) }
    
    // 定期检查设置变化
    LaunchedEffect(Unit) {
        while (true) {
            kotlinx.coroutines.delay(100) // 每100ms检查一次
            val newMaxLevelSetting = settingsStorage.getCalculatorDefaultMaxLevelAmber()
            if (newMaxLevelSetting != currentMaxLevelAmber) {
                currentMaxLevelAmber = newMaxLevelSetting
            }
            val newAllUltimateSetting = settingsStorage.getCalculatorDefaultAllUltimate()
            if (newAllUltimateSetting != currentDefaultAllUltimate) {
                currentDefaultAllUltimate = newAllUltimateSetting
                println("DEBUG: currentDefaultAllUltimate changed to: $currentDefaultAllUltimate")
            }
            val newUsePersonalDataSetting = settingsStorage.getCalculatorUsePersonalData()
            if (newUsePersonalDataSetting != usePersonalData) {
                usePersonalData = newUsePersonalDataSetting
                println("DEBUG: usePersonalData changed to: $usePersonalData")
            }
        }
    }
    
    // 贵客率详情弹窗状态
    var showGuestRateDetailDialog by remember { mutableStateOf(false) }
    var selectedChefForDetail by remember { mutableStateOf<com.example.show_auto.data.Chef?>(null) }
    
    // 当状态改变时自动保存
    LaunchedEffect(onlyShowOwned, onlyShowUltimateChefs, onlyShowAssassinChefs) {
        settingsStorage.saveCalculatorFilterStates(
            onlyShowOwned = onlyShowOwned,
            onlyShowAuraChefs = true, // 固定为true，不再保存状态
            onlyShowUltimateChefs = onlyShowUltimateChefs,
            onlyShowAssassinChefs = onlyShowAssassinChefs
        )
    }

    // 技能信息数据类
    data class ChefSkillInfo(
        val skillCount: Int = 0,
        val giftQuantityPercentage: Double = 0.0, // 稀有客人赠礼数量的第一个变量
        val specialSortValue: Double = 0.0 // 特殊排序值
    )

    // 计算厨师技能优先级和详细信息的函数
    fun getChefSkillPriority(chef: com.example.show_auto.data.Chef, skills: List<com.example.show_auto.data.Skill>): Triple<Int, Double, ChefSkillInfo> {
        // 获取基础技能和修炼技能描述
        val baseSkillDesc = if (chef.skill > 0) {
            skills.find { it.skillId == chef.skill }?.desc ?: ""
        } else {
            ""
        }
        val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(chef, skills, currentDefaultAllUltimate)
        val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
        
        // 提取技能描述中的数值
        fun extractPercentage(text: String, patterns: List<String>): Double {
            for (pattern in patterns) {
                val regex = pattern.toRegex()
                val match = regex.find(text)
                if (match != null) {
                    val value = match.groupValues.getOrNull(1)?.toDoubleOrNull()
                    if (value != null) return value
                }
            }
            return 0.0
        }
        
        // 计算技能命中数量
        fun countMatchedSkills(): Int {
            var count = 0
            
            // 检查所有技能类型
            val allPatterns = listOf(
                "每制作一种神级料理贵客赠礼翻倍概率\\+(\\d+(?:\\.\\d+)?)%",
                "稀有客人赠礼数量.*?(\\d+(?:\\.\\d+)?)%.*?概率提升.*?(\\d+(?:\\.\\d+)?)%",
                "每制作一种神级料理稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%",
                "场上厨师制作特级及以上料理时此料理贵客符文概率\\+(\\d+(?:\\.\\d+)?)%",
                "场上男性厨师稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%",
                "场上女性厨师贵客率\\+(\\d+(?:\\.\\d+)?)%",
                "稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%",
                "开业时间-(\\d+(?:\\.\\d+)?)%",
                "厨具技能效果翻倍"
            )
            
            for (pattern in allPatterns) {
                if (pattern.toRegex().find(combinedSkillDesc) != null) {
                    count++
                }
            }
            
            return count
        }
        
        val skillCount = countMatchedSkills()
        
        // 1. 每制作一种神级料理贵客赠礼翻倍概率
        val doubleGiftPattern = "每制作一种神级料理贵客赠礼翻倍概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
        val doubleGiftMatch = doubleGiftPattern.find(combinedSkillDesc)
        if (doubleGiftMatch != null) {
            val value = doubleGiftMatch.groupValues[1].toDoubleOrNull() ?: 0.0
            return Triple(1, value, ChefSkillInfo(skillCount, 0.0, value))
        }
        
        // 2. 稀有客人赠礼数量概率提升
        val giftQuantityPattern = "稀有客人赠礼数量.*?(\\d+(?:\\.\\d+)?)%.*?概率提升.*?(\\d+(?:\\.\\d+)?)%".toRegex()
        val giftQuantityMatch = giftQuantityPattern.find(combinedSkillDesc)
        if (giftQuantityMatch != null) {
            val giftQuantity = giftQuantityMatch.groupValues[1].toDoubleOrNull() ?: 0.0
            val probabilityIncrease = giftQuantityMatch.groupValues[2].toDoubleOrNull() ?: 0.0
            val maxValue = maxOf(giftQuantity, probabilityIncrease)
            return Triple(2, maxValue, ChefSkillInfo(skillCount, giftQuantity, maxValue))
        }
        
        // 每制作一种神级料理稀有客人出现概率
        val godRecipePattern = "每制作一种神级料理稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
        val godRecipeMatch = godRecipePattern.find(combinedSkillDesc)
        if (godRecipeMatch != null) {
            val value = godRecipeMatch.groupValues[1].toDoubleOrNull() ?: 0.0
            return Triple(2, value, ChefSkillInfo(skillCount, 0.0, value))
        }
        
        // 3. 场上厨师制作特级及以上料理时此料理贵客符文概率
        val runePattern = "场上厨师制作特级及以上料理时此料理贵客符文概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
        val runeMatch = runePattern.find(combinedSkillDesc)
        if (runeMatch != null) {
            val value = runeMatch.groupValues[1].toDoubleOrNull() ?: 0.0
            return Triple(3, value, ChefSkillInfo(skillCount, 0.0, value))
        }
        
        // 4. 场上男性/女性厨师贵客率
        val genderPatterns = listOf(
            "场上男性厨师稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%".toRegex(),
            "场上女性厨师贵客率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
        )
        for (pattern in genderPatterns) {
            val match = pattern.find(combinedSkillDesc)
            if (match != null) {
                val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
                return Triple(4, value, ChefSkillInfo(skillCount, 0.0, value))
            }
        }
        
        // 5. 稀有客人出现概率
        val generalPattern = "稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
        val generalMatch = generalPattern.find(combinedSkillDesc)
        if (generalMatch != null) {
            val value = generalMatch.groupValues[1].toDoubleOrNull() ?: 0.0
            return Triple(5, value, ChefSkillInfo(skillCount, 0.0, value))
        }
        
        // 6. 开业时间减少
        val timePattern = "开业时间-(\\d+(?:\\.\\d+)?)%".toRegex()
        val timeMatch = timePattern.find(combinedSkillDesc)
        if (timeMatch != null) {
            val value = timeMatch.groupValues[1].toDoubleOrNull() ?: 0.0
            return Triple(6, value, ChefSkillInfo(skillCount, 0.0, value))
        }
        
        // 7. 厨具技能效果翻倍
        if (combinedSkillDesc.contains("厨具技能效果翻倍")) {
            return Triple(7, 100.0, ChefSkillInfo(skillCount, 0.0, 100.0)) // 给予较高的排序值
        }
        
        // 默认：无特殊技能
        return Triple(8, 0.0, ChefSkillInfo(skillCount, 0.0, 0.0))
    }

    // 检查厨师是否有开业时间相关技能
    fun hasOpeningTimeSkill(chef: com.example.show_auto.data.Chef, skills: List<com.example.show_auto.data.Skill>): Boolean {
        // 获取基础技能和修炼技能描述
        val baseSkillDesc = if (chef.skill > 0) {
            skills.find { it.skillId == chef.skill }?.desc ?: ""
        } else {
            ""
        }
        val ultimateSkillDesc = getChefSkillDescription(chef, skills)
        val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
        
        // 检查是否包含开业时间相关技能
        val openingTimePatterns = listOf(
            "开业时间\\+(\\d+(?:\\.\\d+)?)%",
            "开业时间-(\\d+(?:\\.\\d+)?)%"
        )
        
        return openingTimePatterns.any { pattern ->
            pattern.toRegex().find(combinedSkillDesc) != null
        }
    }
    
    // 获取厨师的时间加成数值（正值表示增加时间，负值表示减少时间）
    fun getChefOpeningTimeBonus(chef: com.example.show_auto.data.Chef, skills: List<com.example.show_auto.data.Skill>): Double {
        // 获取基础技能和修炼技能描述
        val baseSkillDesc = if (chef.skill > 0) {
            skills.find { it.skillId == chef.skill }?.desc ?: ""
        } else {
            ""
        }
        val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(chef, skills, currentDefaultAllUltimate)
        val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
        
        var totalBonus = 0.0
        
        // 匹配开业时间相关的技能，分别处理减号和加号
        val openingTimeMinusPattern = "开业时间-(\\d+(?:\\.\\d+)?)%".toRegex()
        val openingTimePlusPattern = "开业时间\\+(\\d+(?:\\.\\d+)?)%".toRegex()
        
        // 从厨师技能中提取开业时间加成
        // 处理减号（-）的情况，减少时间
        val minusMatches = openingTimeMinusPattern.findAll(combinedSkillDesc)
        for (match in minusMatches) {
            val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
            totalBonus -= value // 减号表示减少时间，所以是负值
        }
        
        // 处理加号（+）的情况，增加时间
        val plusMatches = openingTimePlusPattern.findAll(combinedSkillDesc)
        for (match in plusMatches) {
            val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
            totalBonus += value // 加号表示增加时间，所以是正值
        }
        
        return totalBonus
    }
    
    // 检查厨师是否有暴击技能
    fun hasCritSkill(chef: com.example.show_auto.data.Chef, skills: List<com.example.show_auto.data.Skill>, defaultAllUltimate: Boolean = false): Boolean {
        // 获取基础技能和修炼技能描述
        val baseSkillDesc = if (chef.skill > 0) {
            skills.find { it.skillId == chef.skill }?.desc ?: ""
        } else {
            ""
        }
        val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(chef, skills, currentDefaultAllUltimate)
        val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
        
        // 检查是否包含暴击相关技能模式
        val critPatterns = listOf(
            "稀有客人赠礼数量\\d+%概率提升\\d+%", // 稀有客人赠礼数量X%概率提升X%
            "每制作一种神级料理贵客赠礼翻倍概率\\+\\d+(?:\\.\\d+)?%", // 每制作一种神级料理贵客赠礼翻倍概率+*%
            "贵客赠礼数量\\d+%概率提升\\d+%" // 贵客赠礼数量*%概率提升*%
        )
        
        return critPatterns.any { pattern ->
            pattern.toRegex().find(combinedSkillDesc) != null
        }
    }
    


    // 过滤厨师列表 - 根据开关状态决定是否只显示已拥有的厨师，支持技能搜索、贵客厨师筛选、已修炼厨师筛选和刺客厨师筛选
    val filteredChefs = remember(chefs, selectedChefs, searchText, onlyShowOwned, onlyShowAuraChefs, onlyShowUltimateChefs, onlyShowCritChefs, onlyShowAssassinChefs, skills) {
        chefs.filter { chef ->
            // 基础过滤：排除已选择的厨师和搜索匹配（名称、技能描述或来源）
            val searchMatches = if (searchText.isEmpty()) {
                true
            } else {
                // 匹配厨师名称
                val nameMatches = chef.name.contains(searchText, ignoreCase = true)
                // 匹配技能描述
                val skillMatches = getChefSkillDescription(chef, skills).contains(searchText, ignoreCase = true)
                // 匹配厨师来源
                val originMatches = chef.origin.contains(searchText, ignoreCase = true)
                nameMatches || skillMatches || originMatches
            }

            // 贵客厨师筛选
            val auraMatches = if (onlyShowAuraChefs) {
                isAuraChef(chef, skills) // 使用贵客厨师筛选逻辑
            } else {
                true
            }

            // 暴击技能筛选
            val critMatches = if (onlyShowCritChefs) {
                hasCritSkill(chef, skills, currentDefaultAllUltimate) // 只显示有暴击技能的厨师
            } else {
                true
            }

            // 修炼状态筛选 - 修复逻辑：当两个都开启时显示所有厨师
            val cultivationMatches = when {
                onlyShowUltimateChefs && onlyShowAssassinChefs -> true // 两个都开启：显示所有厨师
                onlyShowUltimateChefs -> chef.ult // 只开启"查询已修"：只显示已修炼厨师
                onlyShowAssassinChefs -> hasOpeningTimeSkill(chef, skills) // 只开启"查询刺客"：只显示有开业时间技能的厨师
                else -> true // 两个都不开启：显示所有厨师
            }

            (!onlyShowOwned || chef.got) && // 默认只显示已拥有的厨师，点击"查询全部"后显示所有厨师
            !selectedChefs.filter { it.name.isNotEmpty() }.contains(chef) && searchMatches && auraMatches && critMatches && cultivationMatches
        }.sortedWith { chef1, chef2 ->
            // 如果开启了查询暴击，按照星级降序、暴击降序、贵客率降序排序
            if (onlyShowCritChefs) {
                // 首先按星级降序排序（高星级优先）
                val rarityComparison = chef2.rarity.compareTo(chef1.rarity)
                if (rarityComparison != 0) {
                    rarityComparison
                } else {
                    // 同星级内，按总暴击率降序排序
                    val critRate1 = if (usePersonalData) {
                        calculateTotalCritRate(chef1, skills, gameData, personalData, currentDefaultAllUltimate)
                    } else {
                        calculateTotalCritRate(chef1, skills, gameData, null, currentDefaultAllUltimate)
                    }
                    val critRate2 = if (usePersonalData) {
                        calculateTotalCritRate(chef2, skills, gameData, personalData, currentDefaultAllUltimate)
                    } else {
                        calculateTotalCritRate(chef2, skills, gameData, null, currentDefaultAllUltimate)
                    }
                    val critRateComparison = critRate2.compareTo(critRate1)
                    if (critRateComparison != 0) {
                        critRateComparison
                    } else {
                        // 暴击率相同时，按总贵客率降序排序
                        val guestRate1 = if (usePersonalData) {
                            calculateTotalGuestRateBonusWithMaxAmber(chef1, skills, gameData, personalData, currentMaxLevelAmber, currentDefaultAllUltimate)
                        } else {
                            calculateTotalGuestRateBonusWithMaxAmber(chef1, skills, gameData, null, currentMaxLevelAmber, currentDefaultAllUltimate)
                        }
                        val guestRate2 = if (usePersonalData) {
                            calculateTotalGuestRateBonusWithMaxAmber(chef2, skills, gameData, personalData, currentMaxLevelAmber, currentDefaultAllUltimate)
                        } else {
                            calculateTotalGuestRateBonusWithMaxAmber(chef2, skills, gameData, null, currentMaxLevelAmber, currentDefaultAllUltimate)
                        }
                        val guestRateComparison = guestRate2.compareTo(guestRate1)
                        if (guestRateComparison != 0) {
                            guestRateComparison
                        } else {
                            // 贵客率相同时，按厨师名称排序（保证排序稳定性）
                            chef1.name.compareTo(chef2.name)
                        }
                    }
                }
            } else {
                // 默认排序逻辑：先按星级降序，再按总贵客率降序
                val rarityComparison = chef2.rarity.compareTo(chef1.rarity)
                if (rarityComparison != 0) {
                    rarityComparison
                } else {
                                    // 同星级内，按总贵客率降序排序
                val guestRate1 = if (usePersonalData) {
                    calculateTotalGuestRateBonusWithMaxAmber(chef1, skills, gameData, personalData, currentMaxLevelAmber, currentDefaultAllUltimate)
                } else {
                    calculateTotalGuestRateBonusWithMaxAmber(chef1, skills, gameData, null, currentMaxLevelAmber, currentDefaultAllUltimate)
                }
                val guestRate2 = if (usePersonalData) {
                    calculateTotalGuestRateBonusWithMaxAmber(chef2, skills, gameData, personalData, currentMaxLevelAmber, currentDefaultAllUltimate)
                } else {
                    calculateTotalGuestRateBonusWithMaxAmber(chef2, skills, gameData, null, currentMaxLevelAmber, currentDefaultAllUltimate)
                }
                    val guestRateComparison = guestRate2.compareTo(guestRate1)
                    if (guestRateComparison != 0) {
                        guestRateComparison
                    } else {
                        // 贵客率相同时，按厨师名称排序（保证排序稳定性）
                        chef1.name.compareTo(chef2.name)
                    }
                }
            }
        }
    }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text("选择厨师")
        },
        text = {
            Column {
                // 筛选按钮组 - 移动到标题下方
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 12.dp),
                    horizontalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    // 查询全部按钮
                    Button(
                        onClick = { onlyShowOwned = !onlyShowOwned },
                        modifier = Modifier
                            .weight(1f)
                            .height(32.dp),
                        shape = RoundedCornerShape(6.dp),
                        contentPadding = PaddingValues(horizontal = 4.dp, vertical = 4.dp),
                        border = BorderStroke(1.dp, Color.Black),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (!onlyShowOwned)  // 反转逻辑
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.surfaceVariant,
                            contentColor = if (!onlyShowOwned)  // 反转逻辑
                                MaterialTheme.colorScheme.onPrimary
                            else
                                MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    ) {
                        Text(
                            text = "查询全部",
                            fontSize = 12.sp
                        )
                    }

                    // 查询暴击按钮
                    Button(
                        onClick = { 
                            onlyShowCritChefs = !onlyShowCritChefs
                            
                            // 打印关羽的技能信息进行调试
                            val guanyu = chefs.find { it.name == "关羽" }
                            if (guanyu != null) {
                                println("=== 关羽技能调试信息 ===")
                                println("关羽ID: ${guanyu.chefId}, 技能ID: ${guanyu.skill}, 修炼技能列表: ${guanyu.ultimateSkillList}")
                                
                                // 基础技能
                                val baseSkill = skills.find { it.skillId == guanyu.skill }
                                println("基础技能: ${baseSkill?.desc ?: "未找到"}")
                                
                                // 修炼技能
                                val ultimateSkills = guanyu.ultimateSkillList.mapNotNull { skillId ->
                                    skills.find { it.skillId == skillId }?.desc
                                }
                                println("修炼技能: ${ultimateSkills.joinToString("; ")}")
                                
                                // 检测暴击技能
                                val hasCrit = hasCritSkill(guanyu, skills, currentDefaultAllUltimate)
                                println("是否有暴击技能: $hasCrit")
                                
                                // 合并技能描述
                                val baseSkillDesc = baseSkill?.desc ?: ""
                                val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(guanyu, skills, currentDefaultAllUltimate)
                                val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
                                println("合并技能描述: $combinedSkillDesc")
                                
                                // 测试各个暴击技能模式
                                val critPatterns = listOf(
                                    "稀有客人赠礼数量\\d+%概率提升\\d+%",
                                    "每制作一种神级料理贵客赠礼翻倍概率\\+\\d+(?:\\.\\d+)?%",
                                    "贵客赠礼数量\\d+%概率提升\\d+%"
                                )
                                
                                critPatterns.forEachIndexed { index, pattern ->
                                    val regex = pattern.toRegex()
                                    val match = regex.find(combinedSkillDesc)
                                    println("模式${index + 1} [$pattern]: ${if (match != null) "匹配 - ${match.value}" else "不匹配"}")
                                }
                                println("========================")
                            } else {
                                println("未找到关羽")
                            }
                        },
                        modifier = Modifier
                            .weight(1f)
                            .height(32.dp),
                        shape = RoundedCornerShape(6.dp),
                        contentPadding = PaddingValues(0.dp), // 移除内边距，让文字居中
                        border = BorderStroke(1.dp, Color.Black),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (onlyShowCritChefs)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.surfaceVariant,
                            contentColor = if (onlyShowCritChefs)
                                MaterialTheme.colorScheme.onPrimary
                            else
                                MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    ) {
                        Text(
                            text = "查询暴击",
                            fontSize = 12.sp,
                            textAlign = TextAlign.Center // 添加文字居中
                        )
                    }

                    // 查询刺客按钮
                    Button(
                        onClick = { onlyShowAssassinChefs = !onlyShowAssassinChefs },
                        modifier = Modifier
                            .weight(1f)
                            .height(32.dp),
                        shape = RoundedCornerShape(6.dp),
                        contentPadding = PaddingValues(0.dp), // 移除内边距，让文字居中
                        border = BorderStroke(1.dp, Color.Black),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (onlyShowAssassinChefs)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.surfaceVariant,
                            contentColor = if (onlyShowAssassinChefs)
                                MaterialTheme.colorScheme.onPrimary
                            else
                                MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    ) {
                        Text(
                            text = "查询刺客",
                            fontSize = 12.sp,
                            textAlign = TextAlign.Center // 添加文字居中
                        )
                    }

                    // 查询已修炼按钮
                    Button(
                        onClick = { onlyShowUltimateChefs = !onlyShowUltimateChefs },
                        modifier = Modifier
                            .weight(1f)
                            .height(32.dp),
                        shape = RoundedCornerShape(6.dp),
                        contentPadding = PaddingValues(0.dp), // 移除内边距，让文字居中
                        border = BorderStroke(1.dp, Color.Black),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (onlyShowUltimateChefs)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.surfaceVariant,
                            contentColor = if (onlyShowUltimateChefs)
                                MaterialTheme.colorScheme.onPrimary
                            else
                                MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    ) {
                        Text(
                            text = "查询已修炼",
                            fontSize = 12.sp,
                            textAlign = TextAlign.Center // 添加文字居中
                        )
                    }
                }

                // 搜索框 - 按照web项目的live-search，支持技能搜索
                OutlinedTextField(
                    value = searchText,
                    onValueChange = { searchText = it },
                    label = { Text("查找", fontSize = 13.sp) },
                    placeholder = { Text("输入厨师名称、技能或来源", fontSize = 13.sp) },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                    textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
                    leadingIcon = {
                        Icon(
                            imageVector = Icons.Default.Search,
                            contentDescription = "搜索",
                            modifier = Modifier.size(20.dp)
                        )
                    },
                    trailingIcon = {
                        if (searchText.isNotEmpty()) {
                            IconButton(onClick = { searchText = "" }) {
                                Icon(
                                    imageVector = Icons.Default.Clear,
                                    contentDescription = "清空",
                                    modifier = Modifier.size(18.dp)
                                )
                            }
                        }
                    },
                    shape = RoundedCornerShape(8.dp)
                )

                Spacer(modifier = Modifier.height(8.dp))

                // 厨师列表
                LazyColumn(
                    modifier = Modifier.height(400.dp)
                ) {
                    if (filteredChefs.isEmpty()) {
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                Text(
                                    text = if (searchText.isEmpty()) "没有可选厨师" else "没有找到",
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                        }
                    } else {
                        items(filteredChefs) { chef ->
                            Card(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(vertical = 2.dp)
                                    .clickable { onChefSelected(chef) },
                                elevation = CardDefaults.cardElevation(defaultElevation = 1.dp)
                            ) {
                                Box(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(12.dp)
                                ) {
                                    // 主要内容区域
                                    Column {
                                        // 第一行：厨师名字 + 星级
                                        Row(
                                            verticalAlignment = Alignment.CenterVertically
                                        ) {
                                            Text(
                                                text = chef.name,
                                                fontSize = 16.sp,
                                                fontWeight = FontWeight.Medium
                                            )

                                            Spacer(modifier = Modifier.width(8.dp))

                                            // 星级显示
                                            Row {
                                                repeat(chef.rarity) {
                                                    Icon(
                                                        imageVector = Icons.Default.Star,
                                                        contentDescription = null,
                                                        tint = MaterialTheme.colorScheme.primary,
                                                        modifier = Modifier.size(12.dp)
                                                    )
                                                }
                                            }
                                            
                                            // 厨师来源显示
                                            if (gameData != null) {
                                                val chefData = gameData.chefs.find { it.chefId == chef.chefId }
                                                if (chefData != null && chefData.origin.isNotEmpty()) {
                                                    Spacer(modifier = Modifier.width(8.dp))
                                                    Text(
                                                        text = "来源：${chefData.origin.replace("<br>", "、")}",
                                                        fontSize = 10.sp,
                                                        color = Color(0xFF666666),
                                                        fontStyle = androidx.compose.ui.text.font.FontStyle.Italic
                                                    )
                                                }
                                            }
                                        }

                                                                // 第二行：贵客率总加成和开业时间（只要厨师满足贵客筛选条件就显示）
                        if (isAuraChef(chef, skills)) {
                            // 计算贵客率时考虑场上性别技能
                            // 获取其他已选择的厨师（排除当前对话框位置的厨师）
                            val otherSelectedChefs = selectedChefs.filterIndexed { index, selectedChef -> 
                                index != dialogIndex && selectedChef.name.isNotEmpty() 
                            }
                            
                            // 获取厨师当前佩戴的厨具
                            val chefEquip = if (personalData != null && gameData != null) {
                                val equipId = personalData.chefs[chef.chefId]?.equip
                                if (equipId != null) {
                                    gameData.equips.find { it.equipId == equipId.toString() }
                                } else {
                                    null
                                }
                            } else {
                                null
                            }
                            
                                                        // 先计算基础贵客率（根据"启用厨具遗玉"设置决定是否包含厨具、心法盘）
                            val baseGuestRateBonus = if (usePersonalData) {
                                calculateTotalGuestRateBonusWithMaxAmber(chef, skills, gameData, personalData, currentMaxLevelAmber, currentDefaultAllUltimate)
                            } else {
                                calculateTotalGuestRateBonusWithMaxAmber(chef, skills, gameData, null, currentMaxLevelAmber, currentDefaultAllUltimate)
                            }
                            
                            // 再计算场上性别技能加成，并追踪来源厨师
                            var fieldGenderBonus = 0.0
                            val fieldBonusSources = mutableListOf<Pair<String, Int>>() // 存储 (厨师名称, 加成值)
                            val currentChefGender = if (chef.tags.isNotEmpty()) chef.tags[0] else 0
                            
                            otherSelectedChefs.forEach { otherChef ->
                                if (otherChef.name.isNotEmpty()) {
                                    // 获取其他厨师的基础技能和修炼技能描述
                                    val baseSkillDesc = if (otherChef.skill > 0) {
                                        skills.find { it.skillId == otherChef.skill }?.desc ?: ""
                                    } else {
                                        ""
                                    }
                                    
                                    val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(otherChef, skills, currentDefaultAllUltimate)
                                    val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
                                    
                                    // 检查"场上男性厨师稀有客人出现概率+*%"技能
                                    if (currentChefGender == 1) { // 当前厨师是男性
                                        val maleChefPattern = "场上男性厨师稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
                                        val maleChefMatches = maleChefPattern.findAll(combinedSkillDesc)
                                        for (match in maleChefMatches) {
                                            val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
                                            if (value > 0) {
                                                fieldGenderBonus += value
                                                fieldBonusSources.add(Pair(otherChef.name, value.toInt()))
                                            }
                                        }
                                    }
                                    
                                    // 检查"场上女性厨师贵客率+*%"技能
                                    if (currentChefGender == 2) { // 当前厨师是女性
                                        val femaleChefPattern = "场上女性厨师贵客率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
                                        val femaleChefMatches = femaleChefPattern.findAll(combinedSkillDesc)
                                        for (match in femaleChefMatches) {
                                            val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
                                            if (value > 0) {
                                                fieldGenderBonus += value
                                                fieldBonusSources.add(Pair(otherChef.name, value.toInt()))
                                            }
                                        }
                                    }
                                }
                            }
                            
                            val totalGuestRateBonus = baseGuestRateBonus + fieldGenderBonus
                            
                            val openingTimeBonus = if (usePersonalData) {
                                calculateOpeningTimeBonus(chef, chefEquip, skills, gameData, personalData, currentDefaultAllUltimate)
                            } else {
                                calculateOpeningTimeBonus(chef, null, skills, gameData, null, currentDefaultAllUltimate)
                            }
                                            
                                            // 显示条件：有贵客率或有开业时间加成
                                            if (totalGuestRateBonus > 0 || openingTimeBonus != 0.0) {
                                                Row(
                                                    verticalAlignment = Alignment.Top,
                                                    modifier = Modifier
                                                        .padding(top = 4.dp)
                                                        .height(IntrinsicSize.Min) // 让Row高度自适应内容
                                                ) {
                                                    // 贵客率显示（只有当有贵客率时才显示）
                                                    if (totalGuestRateBonus > 0) {
                                                        val guestRateText = if (fieldBonusSources.isNotEmpty()) {
                                                            // 如果有场上技能加成，显示换行格式
                                                            val baseText = "自己${baseGuestRateBonus.toInt()}%"
                                                            val fieldText = fieldBonusSources.joinToString("+") { "${it.first}${it.second}%" }
                                                            val totalText = "${totalGuestRateBonus.toInt()}%"
                                                            "总贵客率：\n$baseText+$fieldText = $totalText"
                                                        } else {
                                                            // 没有场上技能加成时，显示简单格式
                                                            "总贵客率：${totalGuestRateBonus.toInt()}%"
                                                        }
                                                        
                                                        Text(
                                                            text = guestRateText,
                                                            fontSize = 9.sp,
                                                            color = Color(0xFF7B1FA2), // 紫色
                                                            fontWeight = FontWeight.Medium,
                                                            modifier = Modifier
                                                                .background(
                                                                    color = Color(0xFF7B1FA2).copy(alpha = 0.1f), // 紫色背景
                                                                    shape = RoundedCornerShape(4.dp)
                                                                )
                                                                .padding(horizontal = 4.dp, vertical = 2.dp)
                                                        )
                                                    }
                                                    
                                                    // 总暴击率显示
                                                    val totalCritRate = if (usePersonalData) {
                                                        calculateTotalCritRate(chef, skills, gameData, personalData, currentDefaultAllUltimate)
                                                    } else {
                                                        calculateTotalCritRate(chef, skills, gameData, null, currentDefaultAllUltimate)
                                                    }
                                                    if (totalCritRate > 0) {
                                                        if (totalGuestRateBonus > 0) {
                                                            Spacer(modifier = Modifier.width(4.dp))
                                                        }
                                                        
                                                        Text(
                                                            text = "总暴击率：${formatNumber(totalCritRate, 1)}%",
                                                            fontSize = 9.sp,
                                                            color = Color(0xFFE91E63), // 粉色
                                                            fontWeight = FontWeight.Medium,
                                                            modifier = Modifier
                                                                .background(
                                                                    color = Color(0xFFE91E63).copy(alpha = 0.1f), // 粉色背景
                                                                    shape = RoundedCornerShape(4.dp)
                                                                )
                                                                .padding(horizontal = 4.dp, vertical = 2.dp)
                                                        )
                                                    }
                                                    
                                                    // 时间显示（当有开业时间加成时显示）
                                                    if (openingTimeBonus != 0.0) {
                                                        if (totalGuestRateBonus > 0) {
                                                            Spacer(modifier = Modifier.width(4.dp))
                                                        }
                                                        
                                                        val openingTimeText = when {
                                                            openingTimeBonus > 0 -> "时间+${formatPercentage(openingTimeBonus)}%"  // 正数表示增加时间
                                                            else -> "时间${formatPercentage(openingTimeBonus)}%"  // 负数表示减少时间，已经包含负号
                                                        }
                                                        val openingTimeColor = if (openingTimeBonus > 0) {
                                                            Color(0xFFF44336) // 红色，表示增加时间（不利）
                                                        } else {
                                                            Color(0xFF4CAF50) // 绿色，表示减少时间（有利）
                                                        }
                                                        
                                                        Box(
                                                            modifier = Modifier
                                                                .fillMaxHeight() // 填充Row的高度
                                                                .background(
                                                                    color = openingTimeColor.copy(alpha = 0.1f),
                                                                    shape = RoundedCornerShape(4.dp)
                                                                )
                                                                .padding(horizontal = 4.dp, vertical = 2.dp),
                                                            contentAlignment = Alignment.Center
                                                        ) {
                                                            Text(
                                                                text = openingTimeText,
                                                                fontSize = 9.sp,
                                                                color = openingTimeColor,
                                                                fontWeight = FontWeight.Medium
                                                            )
                                                        }
                                                    }
                                                    
                                                    Spacer(modifier = Modifier.width(2.dp))
                                                    
                                                    // 感叹号详情按钮
                                                    Box(
                                                        modifier = Modifier.fillMaxHeight(),
                                                        contentAlignment = Alignment.Center
                                                    ) {
                                                        Icon(
                                                            imageVector = Icons.Default.Info,
                                                            contentDescription = "查看贵客率详情",
                                                            tint = MaterialTheme.colorScheme.primary, // 与星级颜色一致
                                                            modifier = Modifier
                                                                .size(14.dp)
                                                                .clickable { 
                                                                    selectedChefForDetail = chef
                                                                    showGuestRateDetailDialog = true
                                                                }
                                                        )
                                                    }
                                                }
                                            }
                                        }

                                        // 第三行：技能描述（基础技能+修炼技能）
                                        val baseSkillDesc = if (chef.skill > 0) {
                                            skills.find { it.skillId == chef.skill }?.desc ?: ""
                                        } else {
                                            ""
                                        }
                                        val ultimateSkillDesc = getChefSkillDescription(chef, skills)
                                        
                                        val combinedSkillDesc = buildString {
                                            // 添加基础技能
                                            if (baseSkillDesc.isNotEmpty() && baseSkillDesc != "无修炼技能") {
                                                append(baseSkillDesc)
                                            }
                                            
                                            // 添加修炼技能（多个修炼技能已经用顿号分隔）
                                            if (ultimateSkillDesc.isNotEmpty() && ultimateSkillDesc != "无修炼技能") {
                                                if (baseSkillDesc.isNotEmpty() && baseSkillDesc != "无修炼技能") {
                                                    append("\n") // 基础技能和修炼技能之间用换行分隔
                                                }
                                                append(ultimateSkillDesc)
                                            }
                                        }
                                        
                                        if (combinedSkillDesc.isNotEmpty()) {
                                            Text(
                                                text = combinedSkillDesc,
                                                fontSize = 11.sp, // 从12.sp减小到11.sp
                                                color = MaterialTheme.colorScheme.primary,
                                                modifier = Modifier
                                                    .padding(top = 4.dp, end = 40.dp), // 只给技能文字添加右边距
                                                lineHeight = 14.sp // 相应调整行高
                                            )
                                        }


                                    }
                                    
                                    // 右下角：拥有状态和修炼状态
                                    Column(
                                        modifier = Modifier.align(Alignment.BottomEnd),
                                        horizontalAlignment = Alignment.End
                                    ) {
                                        // 拥有状态
                                        Text(
                                            text = if (chef.got) "已拥有" else "未拥有",
                                            fontSize = 9.sp,
                                            color = if (chef.got)
                                                MaterialTheme.colorScheme.primary
                                            else
                                                Color.Red,
                                            fontWeight = if (chef.got) FontWeight.Bold else FontWeight.Normal
                                        )

                                        // 只有已拥有的厨师才显示修炼状态
                                        if (chef.got) {
                                            Text(
                                                text = if (chef.ult) "已修炼" else "未修炼",
                                                fontSize = 9.sp,
                                                color = if (chef.ult)
                                                    MaterialTheme.colorScheme.primary
                                                else
                                                    Color.Red,
                                                fontWeight = if (chef.ult) FontWeight.Bold else FontWeight.Normal
                                            )
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },
        confirmButton = {
            Row {
                if (searchText.isNotEmpty()) {
                    TextButton(onClick = { searchText = "" }) {
                        Text("清空搜索")
                    }
                }
                TextButton(onClick = {
                    onClearCurrentChef() // 只清空当前选择框的厨师数据
                    onDismiss() // 关闭对话框
                }) {
                    Text("清空当前")
                }
                TextButton(onClick = onDismiss) {
                    Text("关闭")
                }
            }
        }
    )
    
    // 贵客率详情弹窗
    if (showGuestRateDetailDialog && selectedChefForDetail != null) {
        // 构建其他厨师列表（除了当前查看的厨师）
        val otherChefs = selectedChefs.filter { it.chefId != selectedChefForDetail!!.chefId }
        
        GuestRateDetailDialog(
            chef = selectedChefForDetail!!,
            skills = skills,
            gameData = gameData,
            personalData = personalData,
            defaultMaxLevelAmber = currentMaxLevelAmber,
            defaultAllUltimate = currentDefaultAllUltimate,
            onDismiss = { 
                showGuestRateDetailDialog = false
                selectedChefForDetail = null
            },
            otherSelectedChefs = otherChefs
        )
    }
}

/**
 * 计算场上性别技能对已选择厨师的额外加成
 * @param selectedChefs 已选择的厨师列表
 * @param skills 技能数据列表
 * @return 场上性别技能提供的额外贵客率加成
 */
private fun calculateFieldGenderSkillBonus(
    selectedChefs: List<com.example.show_auto.data.Chef>,
    skills: List<com.example.show_auto.data.Skill>,
    defaultAllUltimate: Boolean = false
): Double {
    var totalBonus = 0.0
    
    // 统计场上男性厨师和女性厨师的数量
    val maleChefCount = selectedChefs.count { chef -> 
        chef.name.isNotEmpty() && chef.tags.isNotEmpty() && chef.tags[0] == 1 
    }
    val femaleChefCount = selectedChefs.count { chef -> 
        chef.name.isNotEmpty() && chef.tags.isNotEmpty() && chef.tags[0] == 2 
    }
    
    // 遍历所有已选择的厨师，检查他们的技能
    selectedChefs.forEach { chef ->
        if (chef.name.isNotEmpty()) {
            // 获取厨师的基础技能和修炼技能描述
            val baseSkillDesc = if (chef.skill > 0) {
                skills.find { it.skillId == chef.skill }?.desc ?: ""
            } else {
                ""
            }
            
            val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(chef, skills, defaultAllUltimate)
            val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
            
            // 检查"场上男性厨师稀有客人出现概率+*%"技能
            val maleChefPattern = "场上男性厨师稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
            val maleChefMatches = maleChefPattern.findAll(combinedSkillDesc)
            for (match in maleChefMatches) {
                val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
                // 场上每个男性厨师都提供加成（不包括技能拥有者自己）
                val bonus = value * maleChefCount
                totalBonus += bonus
            }
            
            // 检查"场上女性厨师贵客率+*%"技能
            val femaleChefPattern = "场上女性厨师贵客率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
            val femaleChefMatches = femaleChefPattern.findAll(combinedSkillDesc)
            for (match in femaleChefMatches) {
                val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
                // 场上每个女性厨师都提供加成（不包括技能拥有者自己）
                val bonus = value * femaleChefCount
                totalBonus += bonus
            }
        }
    }
    
    return totalBonus
}

/**
 * 计算厨师贵客率时考虑场上性别技能的影响（用于选择阶段）
 * @param chef 当前厨师
 * @param skills 技能数据列表
 * @param gameData 游戏数据
 * @param personalData 个人数据
 * @param selectedLevel 选择的等级
 * @param selectedAmbers 选择的心法盘
 * @param equip 选择的厨具
 * @param otherSelectedChefs 其他已选择的厨师列表
 * @return 考虑场上性别技能影响后的贵客率
 */
private fun calculateGuestRateWithFieldGenderBonus(
    chef: com.example.show_auto.data.Chef,
    skills: List<com.example.show_auto.data.Skill>,
    gameData: com.example.show_auto.data.GameData?,
    personalData: com.example.show_auto.data.PersonalData?,
    selectedLevel: Int?,
    selectedAmbers: List<com.example.show_auto.data.Amber?>?,
    equip: com.example.show_auto.data.Equip?,
    otherSelectedChefs: List<com.example.show_auto.data.Chef>,
    defaultAllUltimate: Boolean = false
): Double {
    // 基础贵客率计算
    val baseGuestRate = calculateTotalGuestRateBonusWithCalculatorData(
        chef, skills, gameData, personalData, selectedLevel, selectedAmbers, equip, defaultAllUltimate
    )
    
    // 计算来自其他厨师的性别技能加成
    var fieldGenderBonus = 0.0
    
    // 判断当前厨师的性别
    val currentChefGender = if (chef.tags.isNotEmpty()) chef.tags[0] else 0
    
    // 遍历其他已选择的厨师，检查他们的性别技能对当前厨师的影响
    otherSelectedChefs.forEach { otherChef ->
        if (otherChef.name.isNotEmpty()) {
            // 获取其他厨师的基础技能和修炼技能描述
            val baseSkillDesc = if (otherChef.skill > 0) {
                skills.find { it.skillId == otherChef.skill }?.desc ?: ""
            } else {
                ""
            }
            
            val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(otherChef, skills, defaultAllUltimate)
            val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
            
            // 检查"场上男性厨师稀有客人出现概率+*%"技能
            if (currentChefGender == 1) { // 当前厨师是男性
                val maleChefPattern = "场上男性厨师稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
                val maleChefMatches = maleChefPattern.findAll(combinedSkillDesc)
                for (match in maleChefMatches) {
                    val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
                    fieldGenderBonus += value
                }
            }
            
            // 检查"场上女性厨师贵客率+*%"技能
            if (currentChefGender == 2) { // 当前厨师是女性
                val femaleChefPattern = "场上女性厨师贵客率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
                val femaleChefMatches = femaleChefPattern.findAll(combinedSkillDesc)
                for (match in femaleChefMatches) {
                    val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
                    fieldGenderBonus += value
                }
            }
        }
    }
    
    return baseGuestRate + fieldGenderBonus
}

@Composable
private fun CalculatorStarLevelDropdown(
    selectedStarLevel: Int,
    onStarLevelSelected: (Int) -> Unit,
    modifier: Modifier = Modifier
) {
    var expanded by remember { mutableStateOf(false) }
    var cardWidth by remember { mutableStateOf(0.dp) }
    val density = LocalDensity.current
    
    // 星级选项：1-5星降序
    val starLevels = remember { (5 downTo 1).toList() }
    
    Box(modifier = modifier) {
        // 下拉框触发器
        OutlinedCard(
            modifier = Modifier
                .fillMaxWidth()
                .clickable { expanded = true }
                .onGloballyPositioned { coordinates ->
                    cardWidth = with(density) { coordinates.size.width.toDp() }
                },
            border = BorderStroke(
                width = 1.dp,
                color = MaterialTheme.colorScheme.outline
            ),
            shape = RoundedCornerShape(4.dp)
        ) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 4.dp, vertical = 0.dp)
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    // 在展开按钮左侧区域显示星级，居中对齐
                    Box(
                        modifier = Modifier.weight(1f),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = "${selectedStarLevel}星",
                            fontSize = 10.sp,
                            fontWeight = FontWeight.Medium,
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis,
                            textAlign = TextAlign.Center,
                            lineHeight = 20.sp
                        )
                    }
                    
                    // 下拉箭头（调小）
                    Icon(
                        imageVector = Icons.Default.ArrowDropDown,
                        contentDescription = "展开",
                        tint = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.size(16.dp)
                    )
                }
            }
        }
        
        // 下拉菜单
        DropdownMenu(
            expanded = expanded,
            onDismissRequest = { expanded = false },
            modifier = Modifier
                .width(cardWidth)
                .heightIn(max = 200.dp)
        ) {
            // 星级列表
            starLevels.forEach { starLevel ->
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(28.dp)
                        .clickable {
                            onStarLevelSelected(starLevel)
                            expanded = false
                        }
                        .padding(horizontal = 16.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "${starLevel}星",
                        fontSize = 9.sp,
                        fontWeight = FontWeight.Medium
                    )
                }
            }
        }
    }
}

/**
 * 品级下拉框组件
 * @param selectedRank 当前选中的品级
 * @param onRankSelected 品级选择回调
 * @param modifier 修饰符
 */
@Composable
private fun CalculatorRankDropdown(
    selectedRank: String,
    onRankSelected: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    var expanded by remember { mutableStateOf(false) }
    var cardWidth by remember { mutableStateOf(0.dp) }
    val density = LocalDensity.current
    
    // 品级选项：传-神-特-优-可（按您要求的顺序）
    val rankOptions = remember { 
        listOf(
            "传" to Color(0xFF9C27B0), // 紫色
            "神" to Color(0xFFF44336), // 红色
            "特" to Color(0xFFFF9800), // 橙色
            "优" to Color(0xFF4CAF50), // 绿色
            "可" to Color(0xFF000000)  // 黑色
        )
    }
    
    Box(modifier = modifier) {
        // 下拉框触发器
        OutlinedCard(
            modifier = Modifier
                .fillMaxWidth()
                .clickable { expanded = true }
                .onGloballyPositioned { coordinates ->
                    cardWidth = with(density) { coordinates.size.width.toDp() }
                },
            border = BorderStroke(
                width = 1.dp,
                color = MaterialTheme.colorScheme.outline
            ),
            shape = RoundedCornerShape(4.dp)
        ) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 4.dp, vertical = 0.dp)
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                                         // 在展开按钮左侧区域显示品级，居中对齐
                     Box(
                         modifier = Modifier.weight(1f),
                         contentAlignment = Alignment.Center
                     ) {
                         Text(
                             text = selectedRank,
                             fontSize = 10.sp,
                             fontWeight = FontWeight.Medium,
                             maxLines = 1,
                             overflow = TextOverflow.Ellipsis,
                             color = rankOptions.find { it.first == selectedRank }?.second ?: Color.Black,
                             textAlign = TextAlign.Center,
                             lineHeight = 20.sp
                         )
                     }
                     
                     // 下拉箭头（调小）
                     Icon(
                         imageVector = Icons.Default.ArrowDropDown,
                         contentDescription = "展开",
                         tint = MaterialTheme.colorScheme.onSurfaceVariant,
                         modifier = Modifier.size(16.dp)
                     )
                }
            }
        }
        
        // 下拉菜单
        DropdownMenu(
            expanded = expanded,
            onDismissRequest = { expanded = false },
            modifier = Modifier
                .width(cardWidth)
                .heightIn(max = 200.dp)
        ) {
            // 品级列表
            rankOptions.forEach { (rank, color) ->
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(28.dp)
                        .clickable {
                            onRankSelected(rank)
                            expanded = false
                        }
                        .padding(horizontal = 16.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = rank,
                        fontSize = 9.sp,
                        fontWeight = FontWeight.Medium,
                        color = color
                    )
                }
            }
        }
    }
}

@Composable
private fun CalculatorEquipSelectionDialog(
    equips: List<com.example.show_auto.data.Equip>,
    selectedEquips: List<com.example.show_auto.data.Equip>,
    dialogIndex: Int,
    skills: List<com.example.show_auto.data.Skill>,
    onEquipSelected: (com.example.show_auto.data.Equip) -> Unit,
    onClearCurrentEquip: () -> Unit,
    onDismiss: () -> Unit
) {
    val context = LocalContext.current
    val settingsStorage = remember { com.example.show_auto.data.SettingsStorage(context) }
    
    var searchText by remember { mutableStateOf("") }
    var filterRarity1 by remember { mutableStateOf(false) }
    var filterRarity2 by remember { mutableStateOf(false) }
    var filterRarity3 by remember { mutableStateOf(false) }

    // 过滤厨具列表 - 只显示拥有开业时间-*%且值>=5、稀有客人出现概率+*%这两类技能的厨具
    val filteredEquips = remember(equips, searchText, filterRarity1, filterRarity2, filterRarity3, skills) {
        equips.filter { equip ->
            // 技能筛选：只显示拥有开业时间-*%且值>=5、稀有客人出现概率+*%这两类技能的厨具
            val hasValidSkill = hasValidEquipSkill(equip, skills)
            if (!hasValidSkill) return@filter false
            
            // 基础过滤：搜索匹配（名称、技能描述或来源）
            val searchMatches = if (searchText.isEmpty()) {
                true
            } else {
                // 匹配厨具名称
                val nameMatches = equip.name.contains(searchText, ignoreCase = true)
                // 匹配技能描述
                val skillMatches = getEquipSkillDescription(equip, skills).contains(searchText, ignoreCase = true)
                // 匹配厨具来源
                val originMatches = equip.origin.contains(searchText, ignoreCase = true)
                nameMatches || skillMatches || originMatches
            }
            
            if (!searchMatches) return@filter false
            
            // 星级筛选
            val rarityFilter = when {
                filterRarity1 && equip.rarity == 1 -> true
                filterRarity2 && equip.rarity == 2 -> true
                filterRarity3 && equip.rarity == 3 -> true
                !filterRarity1 && !filterRarity2 && !filterRarity3 -> true // 没有星级筛选时显示所有
                else -> false
            }
            
            rarityFilter
        }.sortedWith { equip1, equip2 ->
            try {
                // 首先按星级降序排序
                val rarityComparison = equip2.rarity.compareTo(equip1.rarity)
                if (rarityComparison != 0) {
                    rarityComparison
                } else {
                    // 同星级内，优先展示开业时间-*%值大于5的厨具
                    val hasOpeningTime1 = hasOpeningTimeSkill(equip1, skills)
                    val hasOpeningTime2 = hasOpeningTimeSkill(equip2, skills)
                    
                    if (hasOpeningTime1 && hasOpeningTime2) {
                        // 都有开业时间技能，按数值降序排序
                        val openingTime1 = extractOpeningTimeValue(equip1, skills)
                        val openingTime2 = extractOpeningTimeValue(equip2, skills)
                        openingTime2.compareTo(openingTime1)
                    } else if (hasOpeningTime1 && !hasOpeningTime2) {
                        // equip1有开业时间技能，equip2没有
                        val openingTime1 = extractOpeningTimeValue(equip1, skills)
                        if (openingTime1 >= 5.0) {
                            -1 // equip1优先（开业时间>=5%）
                        } else {
                            // equip1开业时间<5%，按稀有客人概率排序
                            val probability1 = extractGuestRateProbability(equip1, skills)
                            val probability2 = extractGuestRateProbability(equip2, skills)
                            probability2.compareTo(probability1)
                        }
                    } else if (!hasOpeningTime1 && hasOpeningTime2) {
                        // equip2有开业时间技能，equip1没有
                        val openingTime2 = extractOpeningTimeValue(equip2, skills)
                        if (openingTime2 >= 5.0) {
                            1 // equip2优先（开业时间>=5%）
                        } else {
                            // equip2开业时间<5%，按稀有客人概率排序
                            val probability1 = extractGuestRateProbability(equip1, skills)
                            val probability2 = extractGuestRateProbability(equip2, skills)
                            probability2.compareTo(probability1)
                        }
                    } else {
                        // 都没有开业时间技能，按稀有客人概率降序排序
                        val probability1 = extractGuestRateProbability(equip1, skills)
                        val probability2 = extractGuestRateProbability(equip2, skills)
                        probability2.compareTo(probability1)
                    }
                }
            } catch (e: Exception) {
                // 如果排序出错，按名称排序作为后备
                equip1.name.compareTo(equip2.name)
            }
        }
    }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text("选择厨具")
        },
        text = {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .heightIn(max = 600.dp) // 限制对话框最大高度
                    .verticalScroll(rememberScrollState()), // 添加垂直滚动功能
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                // 筛选按钮行 - 三个星级按钮填满一行
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    // 1星按钮
                    Button(
                        onClick = { 
                            try {
                                // 单选模式：点击1星时，取消其他选择
                                filterRarity1 = !filterRarity1
                                if (filterRarity1) {
                                    filterRarity2 = false
                                    filterRarity3 = false
                                }
                                println("1星筛选状态: $filterRarity1")
                            } catch (e: Exception) {
                                println("1星筛选按钮点击异常: ${e.message}")
                            }
                        },
                        modifier = Modifier
                            .weight(1f)
                            .height(32.dp),
                        shape = RoundedCornerShape(6.dp),
                        contentPadding = PaddingValues(horizontal = 4.dp, vertical = 4.dp),
                        border = BorderStroke(1.dp, Color.Black),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (filterRarity1)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.surfaceVariant,
                            contentColor = if (filterRarity1)
                                MaterialTheme.colorScheme.onPrimary
                            else
                                MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    ) {
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            Icon(
                                imageVector = Icons.Default.Star,
                                contentDescription = null,
                                tint = if (filterRarity1)
                                    MaterialTheme.colorScheme.onPrimary // 选中时使用白色
                                else
                                    MaterialTheme.colorScheme.primary, // 未选中时使用深蓝色
                                modifier = Modifier.size(12.dp)
                            )
                        }
                    }
                    
                    // 2星按钮
                    Button(
                        onClick = { 
                            try {
                                // 单选模式：点击2星时，取消其他选择
                                filterRarity2 = !filterRarity2
                                if (filterRarity2) {
                                    filterRarity1 = false
                                    filterRarity3 = false
                                }
                                println("2星筛选状态: $filterRarity2")
                            } catch (e: Exception) {
                                println("2星筛选按钮点击异常: ${e.message}")
                            }
                        },
                        modifier = Modifier
                            .weight(1f)
                            .height(32.dp),
                        shape = RoundedCornerShape(6.dp),
                        contentPadding = PaddingValues(horizontal = 4.dp, vertical = 4.dp),
                        border = BorderStroke(1.dp, Color.Black),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (filterRarity2)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.surfaceVariant,
                            contentColor = if (filterRarity2)
                                MaterialTheme.colorScheme.onPrimary
                            else
                                MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    ) {
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            repeat(2) {
                                Icon(
                                    imageVector = Icons.Default.Star,
                                    contentDescription = null,
                                    tint = if (filterRarity2)
                                        MaterialTheme.colorScheme.onPrimary // 选中时使用白色
                                    else
                                        MaterialTheme.colorScheme.primary, // 未选中时使用深蓝色
                                    modifier = Modifier.size(12.dp)
                                )
                            }
                        }
                    }
                    
                    // 3星按钮
                    Button(
                        onClick = { 
                            try {
                                // 单选模式：点击3星时，取消其他选择
                                filterRarity3 = !filterRarity3
                                if (filterRarity3) {
                                    filterRarity1 = false
                                    filterRarity2 = false
                                }
                                println("3星筛选状态: $filterRarity3")
                            } catch (e: Exception) {
                                println("3星筛选按钮点击异常: ${e.message}")
                            }
                        },
                        modifier = Modifier
                            .weight(1f)
                            .height(32.dp),
                        shape = RoundedCornerShape(6.dp),
                        contentPadding = PaddingValues(horizontal = 4.dp, vertical = 4.dp),
                        border = BorderStroke(1.dp, Color.Black),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (filterRarity3)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.surfaceVariant,
                            contentColor = if (filterRarity3)
                                MaterialTheme.colorScheme.onPrimary
                            else
                                MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    ) {
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            repeat(3) {
                                Icon(
                                    imageVector = Icons.Default.Star,
                                    contentDescription = null,
                                    tint = if (filterRarity3)
                                        MaterialTheme.colorScheme.onPrimary // 选中时使用白色
                                    else
                                        MaterialTheme.colorScheme.primary, // 未选中时使用深蓝色
                                    modifier = Modifier.size(12.dp)
                                )
                            }
                        }
                    }
                }
                
                // 搜索框
                OutlinedTextField(
                    value = searchText,
                    onValueChange = { searchText = it },
                    label = { Text("查找", fontSize = 13.sp) },
                    placeholder = { Text("输入厨具名称、技能或来源", fontSize = 13.sp) },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                    textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
                    leadingIcon = {
                        Icon(
                            imageVector = Icons.Default.Search,
                            contentDescription = "搜索",
                            modifier = Modifier.size(20.dp)
                        )
                    },
                    trailingIcon = {
                        if (searchText.isNotEmpty()) {
                            IconButton(onClick = { searchText = "" }) {
                                Icon(
                                    imageVector = Icons.Default.Clear,
                                    contentDescription = "清空",
                                    modifier = Modifier.size(18.dp)
                                )
                            }
                        }
                    },
                    shape = RoundedCornerShape(8.dp)
                )

                // 厨具列表
                LazyColumn(
                    modifier = Modifier.height(400.dp)
                ) {
                    if (filteredEquips.isEmpty()) {
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                Text(
                                    text = if (searchText.isEmpty()) "没有可选择的厨具" else "没有找到",
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                        }
                    } else {
                        items(filteredEquips) { equip ->
                            Card(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(vertical = 2.dp)
                                    .clickable { onEquipSelected(equip) },
                                elevation = CardDefaults.cardElevation(defaultElevation = 1.dp)
                            ) {
                                Box(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(12.dp)
                                ) {
                                    // 主要内容区域
                                    Column {
                                        // 第一行：厨具名称、星级和来源
                                        Row(
                                            modifier = Modifier.fillMaxWidth(),
                                            verticalAlignment = Alignment.CenterVertically
                                        ) {
                                            Text(
                                                text = equip.name,
                                                fontSize = 16.sp,
                                                fontWeight = FontWeight.Medium
                                            )
                                            Spacer(modifier = Modifier.width(8.dp))
                                            // 显示星级
                                            repeat(equip.rarity) {
                                                Icon(
                                                    imageVector = Icons.Default.Star,
                                                    contentDescription = null,
                                                    tint = MaterialTheme.colorScheme.primary,
                                                    modifier = Modifier.size(12.dp)
                                                )
                                            }
                                            
                                            // 来源放在星级后展示
                                            if (equip.origin.isNotEmpty()) {
                                                Spacer(modifier = Modifier.width(8.dp))
                                                Text(
                                                    text = "来源：${equip.origin.replace("<br>", "、")}",
                                                    fontSize = 10.sp,
                                                    color = Color(0xFF666666),
                                                    fontStyle = androidx.compose.ui.text.font.FontStyle.Italic
                                                )
                                            }
                                        }

                                        // 第二行：技能描述
                                        val skillDescription = getEquipSkillDescriptionWithNewLines(equip, skills)
                                        if (skillDescription.isNotEmpty()) {
                                            Text(
                                                text = skillDescription,
                                                fontSize = 11.sp,
                                                color = MaterialTheme.colorScheme.primary,
                                                modifier = Modifier.padding(top = 4.dp),
                                                lineHeight = 14.sp
                                            )
                                        }
                                        

                                    }
                                }
                            }
                        }
                    }
                }
            }
        },
        confirmButton = {
            Row {
                if (searchText.isNotEmpty()) {
                    TextButton(onClick = { searchText = "" }) {
                        Text("清空搜索")
                    }
                }
                TextButton(onClick = {
                    onClearCurrentEquip() // 清空当前选择框的厨具数据
                    onDismiss() // 关闭对话框
                }) {
                    Text("清空当前")
                }
                TextButton(onClick = onDismiss) {
                    Text("关闭")
                }
            }
        }
    )
}

/**
 * 获取厨具技能描述
 */
private fun getEquipSkillDescription(equip: com.example.show_auto.data.Equip, skills: List<com.example.show_auto.data.Skill>): String {
    if (equip.skill.isEmpty()) return ""

    val skillDescriptions = equip.skill.mapNotNull { skillId ->
        skills.find { it.skillId == skillId }?.desc
    }

    return skillDescriptions.joinToString("\n")
}

/**
 * 获取厨具技能描述（换行展示）
 */
private fun getEquipSkillDescriptionWithNewLines(equip: com.example.show_auto.data.Equip, skills: List<com.example.show_auto.data.Skill>): String {
    val skillDescs = equip.skill.mapNotNull { skillId ->
        skills.find { it.skillId == skillId }?.desc
    }
    return skillDescs.joinToString("\n")
}





/**
 * 检查厨具是否有开业时间技能
 */
private fun hasOpeningTimeSkill(equip: com.example.show_auto.data.Equip, skills: List<com.example.show_auto.data.Skill>): Boolean {
    val skillDescription = getEquipSkillDescription(equip, skills)
    return skillDescription.contains("开业时间-") && skillDescription.contains("%")
}

/**
 * 提取厨具的开业时间数值
 */
private fun extractOpeningTimeValue(equip: com.example.show_auto.data.Equip, skills: List<com.example.show_auto.data.Skill>): Double {
    val skillDescription = getEquipSkillDescription(equip, skills)
    val pattern = "开业时间-(\\d+(?:\\.\\d+)?)%".toRegex()
    val match = pattern.find(skillDescription)
    return match?.groupValues?.getOrNull(1)?.toDoubleOrNull() ?: 0.0
}

/**
 * 提取厨具的贵客率概率数值
 */
private fun extractGuestRateProbability(equip: com.example.show_auto.data.Equip, skills: List<com.example.show_auto.data.Skill>): Double {
    val skillDescription = getEquipSkillDescription(equip, skills)
    val pattern = "稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
    val match = pattern.find(skillDescription)
    return match?.groupValues?.getOrNull(1)?.toDoubleOrNull() ?: 0.0
}

/**
 * 检查厨具是否拥有有效的技能（开业时间-*%且值>=5、稀有客人出现概率+*%）
 */
private fun hasValidEquipSkill(equip: com.example.show_auto.data.Equip, skills: List<com.example.show_auto.data.Skill>): Boolean {
    val skillDescription = getEquipSkillDescription(equip, skills)
    
    // 检查是否有开业时间技能且值>=5%
    val hasOpeningTime = skillDescription.contains("开业时间-") && skillDescription.contains("%")
    if (hasOpeningTime) {
        val openingTimeValue = extractOpeningTimeValue(equip, skills)
        if (openingTimeValue >= 5.0) {
            return true
        }
    }
    
    // 检查是否有稀有客人出现概率技能
    val hasGuestRate = skillDescription.contains("稀有客人出现概率+") && skillDescription.contains("%")
    if (hasGuestRate) {
        val guestRateValue = extractGuestRateProbability(equip, skills)
        if (guestRateValue > 0.0) {
            return true
        }
    }
    
    return false
}

/**
 * 贵客率计算器专用菜谱选择对话框
 */
@Composable
private fun CalculatorRecipeSelectionDialog(
    recipes: List<com.example.show_auto.data.Recipe>,
    selectedRecipes: List<com.example.show_auto.data.Recipe>,
    selectedChefs: List<com.example.show_auto.data.Chef>,
    selectedEquips: List<com.example.show_auto.data.Equip>,
    selectedRecipeSlotIndex: Int,
    skills: List<com.example.show_auto.data.Skill>,
    ultimateSkills: com.example.show_auto.ui.pages.UltimateSkillsState,
    chefInteractions: List<Map<String, Int>>,
    enhancedChef: com.example.show_auto.data.Chef?, // 新增：已经计算好的增强厨师
    onlyShowOwned: Boolean,
    onOnlyShowOwnedChange: (Boolean) -> Unit,
    settingsStorage: com.example.show_auto.data.SettingsStorage,
    gameData: com.example.show_auto.data.GameData?,
    chefAmbers: List<List<com.example.show_auto.data.Amber?>>, // 厨师的心法盘配置列表
    chefLevels: List<Int?>, // 厨师等级列表
    defaultMaxLevelAmber: Boolean, // 心法盘默认满级设置
    onRecipeSelected: (com.example.show_auto.data.Recipe) -> Unit,
    onClearCurrentRecipe: () -> Unit,
    onDismiss: () -> Unit
) {
    var searchText by remember { mutableStateOf("") }

    // 符文分类筛选状态 - 从存储中加载初始值
    var showGoldRunes by remember { mutableStateOf(settingsStorage.getRecipeFilterGoldRunes()) }
    var showSilverRunes by remember { mutableStateOf(settingsStorage.getRecipeFilterSilverRunes()) }
    var showBronzeRunes by remember { mutableStateOf(settingsStorage.getRecipeFilterBronzeRunes()) }
    
    // 符文折叠状态：符文名 -> 是否折叠
    var collapsedRunes by remember { mutableStateOf<Set<String>>(emptySet()) }
    
    // 去掉技法筛选状态，不再需要
    
    // 符文分类定义
    val goldRunes = remember {
        listOf("恐怖利刃", "鼓风机", "蒸馏杯", "千年煮鳖", "香烤鱼排", "五星炒果")
    }
    val silverRunes = remember {
        listOf("刀嘴鹦鹉", "一昧真火", "蒸汽宝石", "耐煮的水草", "焦虫", "暖石")
    }
    val bronzeRunes = remember {
        listOf("剪刀蟹", "油火虫", "蒸汽耳环", "防水的柠檬", "烤焦的菊花", "五香果")
    }
    
    // 当状态改变时自动保存
    LaunchedEffect(showGoldRunes, showSilverRunes, showBronzeRunes) {
        settingsStorage.saveRecipeFilterRuneStates(showGoldRunes, showSilverRunes, showBronzeRunes)
    }
    
    // 去掉技法筛选逻辑，不再根据厨师的修炼任务自动筛选菜谱

    // 过滤和排序菜谱列表
    val filteredRecipes = remember(recipes, selectedRecipes, searchText, onlyShowOwned, showGoldRunes, showSilverRunes, showBronzeRunes, selectedChefs, selectedEquips, selectedRecipeSlotIndex, skills, ultimateSkills, chefInteractions) {
        // 第一步：基础筛选（根据查询全部按钮状态决定是否包含已拥有过滤）
        val baseFiltered = recipes.filter { recipe ->
            // 基础筛选（根据查询全部按钮状态决定是否过滤已拥有菜谱）
            val basicFilter = !selectedRecipes.contains(recipe) &&
            (searchText.isEmpty() ||
             recipe.name.contains(searchText, ignoreCase = true) ||
             (gameData?.guests?.flatMap { guest ->
                 guest.gifts.filter { gift -> gift.recipe == recipe.name }
             }?.firstOrNull()?.antique ?: "").contains(searchText, ignoreCase = true))

            if (!basicFilter) return@filter false

            // 只显示有贵客的菜谱 - 通过贵客礼物判断
            val hasGuestFilter = gameData?.guests?.any { guest ->
                guest.gifts.any { gift -> gift.recipe == recipe.name }
            } ?: false

            if (!hasGuestFilter) return@filter false

            // 符文分类筛选
            val runeName = gameData?.guests?.flatMap { guest ->
                guest.gifts.filter { gift -> gift.recipe == recipe.name }
            }?.firstOrNull()?.antique ?: ""
            
            val runeFilter = when {
                showGoldRunes -> runeName in goldRunes
                showSilverRunes -> runeName in silverRunes
                showBronzeRunes -> runeName in bronzeRunes
                else -> true // 没有符文分类选择时显示所有
            }
            
            if (!runeFilter) return@filter false

            // 根据查询全部按钮状态决定是否过滤已拥有菜谱
            if (!onlyShowOwned) {
                // 开启查询全部时，显示所有菜谱
            true
            } else {
                // 关闭查询全部时，只显示已拥有的菜谱
                recipe.got
            }
        }

        // 获取对应的厨师用于品级排序
        val chefIndex = selectedRecipeSlotIndex / 3
        val chef = selectedChefs.getOrNull(chefIndex)
        val equip = selectedEquips.getOrNull(chefIndex)

        if (enhancedChef != null) {
            // 使用传递进来的已经计算好的增强厨师，不再重新计算

            // 新排序逻辑：神级传级混合按时间排序，特级及以下按品级再按时间排序
            baseFiltered.sortedWith { recipe1, recipe2 ->
                val rank1 = com.example.show_auto.utils.RecipeRankCalculator.calculateRecipeRank(enhancedChef, recipe1)
                val rank2 = com.example.show_auto.utils.RecipeRankCalculator.calculateRecipeRank(enhancedChef, recipe2)
                
                // 检查是否为神级或传级
                val isHighTier1 = rank1 >= 4 // 神级(4)或传级(5)
                val isHighTier2 = rank2 >= 4
                
                when {
                    // 如果都是神/传级，先按符文分组，再按时间排序
                    isHighTier1 && isHighTier2 -> {
                        val rune1 = gameData?.guests?.flatMap { guest ->
                            guest.gifts.filter { gift -> gift.recipe == recipe1.name }
                        }?.firstOrNull()?.antique ?: ""
                        val rune2 = gameData?.guests?.flatMap { guest ->
                            guest.gifts.filter { gift -> gift.recipe == recipe2.name }
                        }?.firstOrNull()?.antique ?: ""
                        
                        val runeComparison = rune1.compareTo(rune2)
                        if (runeComparison != 0) {
                            runeComparison
                        } else {
                            recipe1.time.compareTo(recipe2.time)
                        }
                    }
                    // 如果一个是神/传级，另一个不是，优先神/传级
                    isHighTier1 && !isHighTier2 -> -1
                    !isHighTier1 && isHighTier2 -> 1
                    // 如果都不是神/传级（特级及以下），先按品级，再按符文分组，最后按时间
                    else -> {
                        val rankComparison = rank2.compareTo(rank1) // 品级高到低
                        if (rankComparison != 0) {
                            rankComparison
                        } else {
                            val rune1 = gameData?.guests?.flatMap { guest ->
                                guest.gifts.filter { gift -> gift.recipe == recipe1.name }
                            }?.firstOrNull()?.antique ?: ""
                            val rune2 = gameData?.guests?.flatMap { guest ->
                                guest.gifts.filter { gift -> gift.recipe == recipe2.name }
                            }?.firstOrNull()?.antique ?: ""
                            
                            val runeComparison = rune1.compareTo(rune2)
                            if (runeComparison != 0) {
                                runeComparison
                            } else {
                                recipe1.time.compareTo(recipe2.time) // 时间低到高
                            }
                        }
                    }
                }
            }
        } else {
            // 没有厨师时，按星级降序、符文分组、时间升序排序
            baseFiltered.sortedWith { recipe1, recipe2 ->
                // 首先按星级降序
                val rarityComparison = recipe2.rarity.compareTo(recipe1.rarity)
                if (rarityComparison != 0) {
                    rarityComparison
                } else {
                    // 然后按符文分组
                    val rune1 = gameData?.guests?.flatMap { guest ->
                        guest.gifts.filter { gift -> gift.recipe == recipe1.name }
                    }?.firstOrNull()?.antique ?: ""
                    val rune2 = gameData?.guests?.flatMap { guest ->
                        guest.gifts.filter { gift -> gift.recipe == recipe2.name }
                    }?.firstOrNull()?.antique ?: ""
                    
                    val runeComparison = rune1.compareTo(rune2)
                    if (runeComparison != 0) {
                        runeComparison
                    } else {
                        // 最后按时间升序
                        recipe1.time.compareTo(recipe2.time)
                    }
                }
            }
        }
    }

    // 第二步：直接使用过滤后的菜谱（已拥有过滤已在第一步中处理）
    val displayFilteredRecipes = remember(filteredRecipes) {
            filteredRecipes
    }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
            Text("选择菜谱")
                Button(
                    onClick = { onOnlyShowOwnedChange(!onlyShowOwned) },
                    modifier = Modifier.height(32.dp),
                    shape = RoundedCornerShape(6.dp),
                    contentPadding = PaddingValues(horizontal = 8.dp, vertical = 4.dp),
                    border = BorderStroke(1.dp, Color.Black),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = if (!onlyShowOwned)
                            MaterialTheme.colorScheme.primary
                        else
                            MaterialTheme.colorScheme.surfaceVariant,
                        contentColor = if (!onlyShowOwned)
                            MaterialTheme.colorScheme.onPrimary
                        else
                            MaterialTheme.colorScheme.onSurfaceVariant
                    )
                ) {
                    Text(
                        text = "查询全部",
                        fontSize = 10.sp
                    )
                }
            }
        },
        text = {
            Column {


                // 搜索框
                OutlinedTextField(
                    value = searchText,
                    onValueChange = { searchText = it },
                    label = { Text("查找") },
                    placeholder = { Text("输入菜谱名称或符文名称", fontSize = 12.sp) },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                    leadingIcon = {
                        Icon(
                            imageVector = Icons.Default.Search,
                            contentDescription = "搜索"
                        )
                    },
                    trailingIcon = {
                        if (searchText.isNotEmpty()) {
                            IconButton(onClick = { searchText = "" }) {
                                Icon(
                                    imageVector = Icons.Default.Clear,
                                    contentDescription = "清空"
                                )
                            }
                        }
                    }
                )

                Spacer(modifier = Modifier.height(8.dp))

                // 符文分类筛选按钮行
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 4.dp),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    // 金符文按钮
                    OutlinedButton(
                        onClick = {
                            showGoldRunes = !showGoldRunes
                            if (showGoldRunes) {
                                showSilverRunes = false
                                showBronzeRunes = false
                            }
                        },
                        modifier = Modifier
                            .weight(1f)
                            .height(32.dp),
                        colors = ButtonDefaults.outlinedButtonColors(
                            containerColor = if (showGoldRunes) MaterialTheme.colorScheme.primary else Color.White,
                            contentColor = if (showGoldRunes) Color.White else Color.Black
                        ),
                        shape = RoundedCornerShape(6.dp),
                        border = BorderStroke(1.dp, Color.Black),
                        contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp)
                    ) {
                        Text(
                            text = "金符文",
                            fontSize = 10.sp,
                            fontWeight = FontWeight.Medium
                        )
                    }

                    // 银符文按钮
                    OutlinedButton(
                        onClick = {
                            showSilverRunes = !showSilverRunes
                            if (showSilverRunes) {
                                showGoldRunes = false
                                showBronzeRunes = false
                            }
                        },
                        modifier = Modifier
                            .weight(1f)
                            .height(32.dp),
                        colors = ButtonDefaults.outlinedButtonColors(
                            containerColor = if (showSilverRunes) MaterialTheme.colorScheme.primary else Color.White,
                            contentColor = if (showSilverRunes) Color.White else Color.Black
                        ),
                        shape = RoundedCornerShape(6.dp),
                        border = BorderStroke(1.dp, Color.Black),
                        contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp)
                    ) {
                        Text(
                            text = "银符文",
                            fontSize = 10.sp,
                            fontWeight = FontWeight.Medium
                        )
                    }

                    // 铜符文按钮
                    OutlinedButton(
                        onClick = {
                            showBronzeRunes = !showBronzeRunes
                            if (showBronzeRunes) {
                                showGoldRunes = false
                                showSilverRunes = false
                            }
                        },
                        modifier = Modifier
                            .weight(1f)
                            .height(32.dp),
                        colors = ButtonDefaults.outlinedButtonColors(
                            containerColor = if (showBronzeRunes) MaterialTheme.colorScheme.primary else Color.White,
                            contentColor = if (showBronzeRunes) Color.White else Color.Black
                        ),
                        shape = RoundedCornerShape(6.dp),
                        border = BorderStroke(1.dp, Color.Black),
                        contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp)
                    ) {
                        Text(
                            text = "铜符文",
                            fontSize = 10.sp,
                            fontWeight = FontWeight.Medium
                        )
                    }
                }

                Spacer(modifier = Modifier.height(8.dp))

                // 菜谱列表 - 按符文分组展示，并添加冲突检测
                // 注意：冲突检测使用 filteredRecipes（包含所有菜谱），展示使用 displayFilteredRecipes（已过滤的菜谱）
                val groupedRecipesWithConflict = remember(filteredRecipes, gameData, selectedChefs, selectedEquips, skills, ultimateSkills, chefInteractions) {
                    if (gameData != null) {
                        // 按符文分组
                        val grouped = filteredRecipes.groupBy { recipe ->
                            gameData.guests.flatMap { guest ->
                                guest.gifts.filter { gift -> gift.recipe == recipe.name }
                            }.firstOrNull()?.antique ?: "无符文"
                        }
                        
                        // 为每个符文组添加冲突检测
                        val groupedWithConflict = grouped.mapValues { (runeName, recipes) ->
                            // 使用查询贵客冲突页面的冲突判断逻辑
                            val guests = gameData.guests
                            
                            // 收集该符文下所有菜谱对应的贵客（包括已选择的菜谱）
                            val recipeToGuestsMap = mutableMapOf<String, MutableSet<String>>()
                            
                            // 先收集已选择的菜谱中属于该符文的贵客信息
                            val selectedRecipesInThisRune = selectedRecipes.filter { selectedRecipe ->
                                selectedRecipe.name.isNotEmpty() && // 排除空菜谱
                                gameData.guests.any { guest ->
                                    guest.gifts.any { gift -> 
                                        gift.recipe == selectedRecipe.name && gift.antique == runeName 
                                    }
                                }
                            }
                            
                            // 收集已选择菜谱的贵客信息
                            selectedRecipesInThisRune.forEach { selectedRecipe ->
                                guests.forEach { guest ->
                                    guest.gifts.forEach { gift ->
                                        if (gift.recipe == selectedRecipe.name && gift.antique == runeName) {
                                            recipeToGuestsMap.getOrPut(selectedRecipe.name) { mutableSetOf() }.add(guest.name)
                                        }
                                    }
                                }
                            }
                            
                            // 再收集当前符文组内菜谱的贵客信息
                            recipes.forEach { recipe ->
                                guests.forEach { guest ->
                                    guest.gifts.forEach { gift ->
                                        if (gift.recipe == recipe.name && gift.antique == runeName) {
                                            recipeToGuestsMap.getOrPut(recipe.name) { mutableSetOf() }.add(guest.name)
                                        }
                                    }
                                }
                            }
                            
                            // 按贵客分组菜谱（包含已选择的菜谱和当前符文组的菜谱）
                            val recipesByGuest = mutableMapOf<String, MutableList<Recipe>>()
                            
                            // 先添加已选择的菜谱到对应的贵客组
                            selectedRecipesInThisRune.forEach { selectedRecipe ->
                                val recipeGuests = recipeToGuestsMap[selectedRecipe.name] ?: emptySet()
                                recipeGuests.forEach { guestName ->
                                    val guestRecipes = recipesByGuest.getOrPut(guestName) { mutableListOf() }
                                    if (!guestRecipes.any { it.name == selectedRecipe.name }) {
                                        guestRecipes.add(selectedRecipe)
                                    }
                                }
                            }
                            
                            // 再添加当前符文组的所有菜谱
                            recipes.forEach { recipe ->
                                val recipeGuests = recipeToGuestsMap[recipe.name] ?: emptySet()
                                recipeGuests.forEach { guestName ->
                                    val guestRecipes = recipesByGuest.getOrPut(guestName) { mutableListOf() }
                                    if (!guestRecipes.any { it.name == recipe.name }) {
                                        guestRecipes.add(recipe)
                                    }
                                }
                            }
                            
                            // 冲突检测：同一贵客有多个菜谱时，时间最短的无冲突，其余有冲突
                            // 注意：多贵客菜谱不应该与自己冲突
                            val noConflict = mutableListOf<Recipe>()
                            val conflict = mutableListOf<Recipe>()
                            
                            // 添加调试信息
                            System.out.println("符文 $runeName 的冲突检测:")
                            System.out.println("  已选择的菜谱: ${selectedRecipesInThisRune.map { it.name }}")
                            System.out.println("  当前符文组菜谱: ${recipes.map { it.name }}")
                            System.out.println("  按贵客分组结果:")
                            
                            // 收集所有菜谱的贵客数量信息
                            val recipeGuestCountMap = mutableMapOf<String, Int>()
                            recipes.forEach { recipe ->
                                val guestCount = gameData.guests.count { guest ->
                                    guest.gifts.any { gift -> 
                                        gift.recipe == recipe.name && gift.antique == runeName 
                                    }
                                }
                                recipeGuestCountMap[recipe.name] = guestCount
                            }
                            
                            recipesByGuest.forEach { (guestName, guestRecipes) ->
                                System.out.println("    贵客 $guestName: ${guestRecipes.map { "${it.name}(${it.time}秒)" }}")
                                
                                if (guestRecipes.size == 1) {
                                    // 只有一个菜谱，无冲突
                                    noConflict.addAll(guestRecipes)
                                    System.out.println("      -> 无冲突: ${guestRecipes.map { it.name }}")
                                } else {
                                    // 多个菜谱有冲突，需要特殊处理多贵客菜谱
                                    // 双贵客菜谱时间除以2后再判断
                                    System.out.println("      多个菜谱有冲突，开始时间调整计算:")
                                    
                                    val recipesWithAdjustedTime = guestRecipes.map { recipe ->
                                        // 正确判断贵客数量：通过贵客礼物来判断该菜谱对应多少个贵客
                                        val guestCount = gameData.guests.count { guest ->
                                            guest.gifts.any { gift -> 
                                                gift.recipe == recipe.name && gift.antique == runeName 
                                            }
                                        }
                                        val adjustedTime = if (guestCount >= 2) {
                                            recipe.time / 2.0
                                        } else {
                                            recipe.time.toDouble()
                                        }
                                        Triple(recipe, adjustedTime, guestCount)
                                    }
                                    
                                    // 输出每个菜谱的详细信息
                                    System.out.println("      调整后时间详情:")
                                    recipesWithAdjustedTime.forEach { (recipe, adjustedTime, guestCount) ->
                                        val timeDetail = if (guestCount >= 2) {
                                            "${recipe.name}: ${recipe.time}秒/2 = ${adjustedTime.toInt()}秒 (${guestCount}贵客)"
                                        } else {
                                            "${recipe.name}: ${recipe.time}秒 (${guestCount}贵客)"
                                        }
                                        System.out.println("        $timeDetail")
                                    }
                                    
                                    // 按调整后的时间排序
                                    val sortedByAdjustedTime = recipesWithAdjustedTime.sortedBy { it.second }
                                    
                                    // 选择调整后时间最短的作为无冲突菜谱
                                    val selectedRecipeInfo = sortedByAdjustedTime.first()
                                    val selectedRecipe = selectedRecipeInfo.first
                                    val selectedAdjustedTime = selectedRecipeInfo.second
                                    val selectedGuestCount = selectedRecipeInfo.third
                                    
                                    noConflict.add(selectedRecipe)
                                    
                                    // 其余菜谱都是冲突菜谱
                                    val remainingRecipes = sortedByAdjustedTime.drop(1).map { it.first }
                                    conflict.addAll(remainingRecipes)
                                    
                                    // 输出调试信息
                                    val timeInfo = if (selectedGuestCount >= 2) {
                                        "多贵客菜谱(时间${selectedRecipe.time}秒/2=${selectedAdjustedTime.toInt()}秒)"
                                    } else {
                                        "单贵客菜谱(时间${selectedRecipe.time}秒)"
                                    }
                                    System.out.println("      -> 无冲突: ${selectedRecipe.name} ($timeInfo)")
                                    System.out.println("      -> 有冲突: ${remainingRecipes.map { it.name }}")
                                }
                            }
                            
                            System.out.println("  最终结果:")
                            System.out.println("    无冲突: ${noConflict.map { it.name }}")
                            System.out.println("    有冲突: ${conflict.map { it.name }}")
                            
                            // 从无冲突列表中移除已选择的菜谱（因为已选择的菜谱不应该显示在无冲突列表中）
                            noConflict.removeAll { recipe ->
                                selectedRecipesInThisRune.any { it.name == recipe.name }
                            }
                            
                            // 从冲突列表中移除已选择的菜谱（因为已选择的菜谱不应该显示在冲突列表中）
                            conflict.removeAll { recipe ->
                                selectedRecipesInThisRune.any { it.name == recipe.name }
                            }
                            
                            // 去重并按品级和时间排序
                            // 品级排序：传(5) > 神(4) > 特(3) > 优(2) > 可(1) > 不可制作(0)
                            val rankSortComparator = compareByDescending<Recipe> { recipe ->
                                val chefIndex = selectedRecipeSlotIndex / 3
                                val chef = selectedChefs.getOrNull(chefIndex)
                                val equip = selectedEquips.getOrNull(chefIndex)
                                
                                if (chef != null) {
                                    val enhancedChef = com.example.show_auto.utils.ChefSkillCalculator.applyAllSkills(
                                        chef, ultimateSkills, equip, skills, chefInteractions.getOrNull(chefIndex)
                                    )
                                    com.example.show_auto.utils.RecipeRankCalculator.calculateRecipeRank(enhancedChef, recipe)
                                } else {
                                    // 没有厨师时，按菜谱星级排序
                                    recipe.rarity
                                }
                            }.thenBy { it.time } // 同品级时按时间升序
                            
                            Triple(
                                noConflict.distinctBy { it.name }.sortedWith(rankSortComparator),
                                conflict.distinctBy { it.name }.sortedWith(rankSortComparator),
                                recipes.sortedWith(rankSortComparator)
                            )
                        }
                        
                        // 检查是否有厨师
                        val chefIndex = selectedRecipeSlotIndex / 3
                        val chef = selectedChefs.getOrNull(chefIndex)
                        val equip = selectedEquips.getOrNull(chefIndex)
                        
                        if (chef != null) {
                            // 有厨师时，按特级及以上菜谱数量排序
                            val sortedGroups = groupedWithConflict.mapValues { (_, triple) ->
                                val (noConflict, conflict, all) = triple
                                // 使用品级排序比较器，而不是简单的星级排序
                                val rankSortComparator = compareByDescending<Recipe> { recipe ->
                                    val enhancedChef = com.example.show_auto.utils.ChefSkillCalculator.applyAllSkills(
                                        chef, ultimateSkills, equip, skills, chefInteractions.getOrNull(chefIndex)
                                    )
                                    com.example.show_auto.utils.RecipeRankCalculator.calculateRecipeRank(enhancedChef, recipe)
                                }.thenBy { it.time } // 同品级时按时间升序
                                
                                Triple(
                                    noConflict.sortedWith(rankSortComparator),
                                    conflict.sortedWith(rankSortComparator),
                                    all.sortedWith(rankSortComparator)
                                )
                            }
                            
                            // 计算每个符文组内特级及以上菜谱的数量
                            val runeWithHighRankCount = sortedGroups.mapValues { (_, triple) ->
                                val (noConflict, conflict, _) = triple
                                (noConflict + conflict).count { recipe ->
                                    val enhancedChef = com.example.show_auto.utils.ChefSkillCalculator.applyAllSkills(
                                        chef, ultimateSkills, equip, skills, chefInteractions.getOrNull(chefIndex)
                                    )
                                    val rank = com.example.show_auto.utils.RecipeRankCalculator.calculateRecipeRank(enhancedChef, recipe)
                                    rank >= 3 // 特级及以上（3=特级，4=神级，5=传级）
                                }
                            }
                            
                            // 检查是否所有符文都没有特级及以上菜谱
                            val totalHighRankCount = runeWithHighRankCount.values.sum()
                            
                            if (totalHighRankCount > 0) {
                                // 有特级及以上菜谱时，按特级及以上菜谱数量排序
                            sortedGroups.toList().sortedWith { (rune1, triple1), (rune2, triple2) ->
                                val highRankCount1 = runeWithHighRankCount[rune1] ?: 0
                                val highRankCount2 = runeWithHighRankCount[rune2] ?: 0
                                
                                // 首先按特级及以上菜谱数量降序
                                val countComparison = highRankCount2.compareTo(highRankCount1)
                                if (countComparison != 0) {
                                    countComparison
                                } else {
                                    // 同数量时按符文名称排序
                                    rune1.compareTo(rune2)
                                }
                            }.toMap()
                            } else {
                                // 所有菜谱都没有特级及以上时，按可级+优级数量排序
                                val runeWithMediumRankCount = sortedGroups.mapValues { (_, triple) ->
                                    val (noConflict, conflict, _) = triple
                                    (noConflict + conflict).count { recipe ->
                                        val enhancedChef = com.example.show_auto.utils.ChefSkillCalculator.applyAllSkills(
                                            chef, ultimateSkills, equip, skills, chefInteractions.getOrNull(chefIndex)
                                        )
                                        val rank = com.example.show_auto.utils.RecipeRankCalculator.calculateRecipeRank(enhancedChef, recipe)
                                        rank in 1..2 // 可级(1)和优级(2)
                                    }
                                }
                                
                                sortedGroups.toList().sortedWith { (rune1, triple1), (rune2, triple2) ->
                                    val mediumRankCount1 = runeWithMediumRankCount[rune1] ?: 0
                                    val mediumRankCount2 = runeWithMediumRankCount[rune2] ?: 0
                                    
                                    // 首先按可级+优级菜谱数量降序
                                    val countComparison = mediumRankCount2.compareTo(mediumRankCount1)
                                    if (countComparison != 0) {
                                        countComparison
                                    } else {
                                        // 同数量时按符文名称排序
                                        rune1.compareTo(rune2)
                                    }
                                }.toMap()
                            }
                        } else {
                            // 没有厨师时，按符文星级降序排序（优先展示五星菜谱的符文）
                            val sortedGroups = groupedWithConflict.mapValues { (_, triple) ->
                                val (noConflict, conflict, all) = triple
                                // 没有厨师时，按菜谱星级排序，同星级时按时间升序
                                val raritySortComparator = compareByDescending<Recipe> { it.rarity }.thenBy { it.time }
                                
                                Triple(
                                    noConflict.sortedWith(raritySortComparator),
                                    conflict.sortedWith(raritySortComparator),
                                    all.sortedWith(raritySortComparator)
                                )
                            }
                            
                            // 按符文名称排序，但优先展示有五星菜谱的符文
                            val runeWithMaxRarity = sortedGroups.mapValues { (_, triple) ->
                                val (noConflict, conflict, _) = triple
                                (noConflict + conflict).maxOfOrNull { it.rarity } ?: 0
                            }
                            
                            sortedGroups.toList().sortedWith { (rune1, triple1), (rune2, triple2) ->
                                val maxRarity1 = runeWithMaxRarity[rune1] ?: 0
                                val maxRarity2 = runeWithMaxRarity[rune2] ?: 0
                                
                                // 首先按最高星级降序
                                val rarityComparison = maxRarity2.compareTo(maxRarity1)
                                if (rarityComparison != 0) {
                                    rarityComparison
                                } else {
                                    // 同星级按符文名称排序
                                    rune1.compareTo(rune2)
                                }
                            }.toMap()
                        }
                    } else {
                        mapOf("无符文" to Triple(emptyList<Recipe>(), emptyList<Recipe>(), filteredRecipes.sortedByDescending { it.rarity }))
                    }
                }

            LazyColumn(
                    modifier = Modifier.height(400.dp)
                ) {
                    if (displayFilteredRecipes.isEmpty()) {
                        item {
                            Box(
                modifier = Modifier
                    .fillMaxWidth()
                                    .padding(16.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                Text(
                                    text = if (searchText.isEmpty()) {
                                        if (onlyShowOwned) "暂无已拥有的菜谱" else "没有可选菜谱"
                                    } else {
                                        "没有找到"
                                    },
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                        }
                    } else {
                        // 遍历每个符文分组
                        groupedRecipesWithConflict.forEach { (runeName, triple) ->
                            val (noConflictRecipes, conflictRecipes, allRecipes) = triple
                            
                            // 直接使用符文分组中的菜谱（已拥有过滤已在基础筛选阶段处理）
                            val displayNoConflictRecipes = noConflictRecipes
                            val displayConflictRecipes = conflictRecipes
                            val displayAllRecipes = allRecipes
                            
                            val totalRecipes = displayAllRecipes.size
                            val noConflictCount = displayNoConflictRecipes.size
                            val conflictCount = displayConflictRecipes.size
                            
                            // 如果该符文分组下没有可显示的菜谱，跳过显示
                            if (totalRecipes == 0) return@forEach
                            
                            item(key = "group_$runeName") {
                    Card(
                        modifier = Modifier
                            .fillMaxWidth()
                                        .padding(vertical = 4.dp),
                        colors = CardDefaults.cardColors(
                                        containerColor = MaterialTheme.colorScheme.primaryContainer
                                    )
                                ) {
                                    Column {
                                        // 符文标题行：符文名称 + 收起展开按钮
                                        Row(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .padding(12.dp),
                                            verticalAlignment = Alignment.CenterVertically,
                                            horizontalArrangement = Arrangement.SpaceBetween
                                        ) {
                                        Text(
                                            text = "$runeName ($totalRecipes)",
                                            fontSize = 14.sp,
                                            fontWeight = FontWeight.Bold,
                                                color = MaterialTheme.colorScheme.onPrimaryContainer
                                            )
                                            
                                            // 收起展开按钮
                                            IconButton(
                                                onClick = {
                                                    collapsedRunes = if (runeName in collapsedRunes) {
                                                        collapsedRunes - runeName
                                                    } else {
                                                        collapsedRunes + runeName
                                                    }
                                                },
                                                modifier = Modifier.size(24.dp)
                                            ) {
                                                Icon(
                                                    imageVector = if (runeName in collapsedRunes) Icons.Default.KeyboardArrowDown else Icons.Default.KeyboardArrowUp,
                                                    contentDescription = if (runeName in collapsedRunes) "展开" else "收起",
                                                    tint = MaterialTheme.colorScheme.onPrimaryContainer,
                                                    modifier = Modifier.size(20.dp)
                                                )
                                            }
                                        }
                                        
                                        // 根据折叠状态决定是否显示内容
                                        if (runeName !in collapsedRunes) {
                                        // 添加tab切换按钮
                                        var selectedTabIndex by remember { mutableStateOf(0) }
                                        
                                        // 自定义标签页头部 - 胶囊样式
                                        Card(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .padding(horizontal = 12.dp, vertical = 4.dp),
                                            shape = RoundedCornerShape(16.dp),
                                            colors = CardDefaults.cardColors(
                                                containerColor = Color(0xFFE3F2FD)
                                            ),
                                            elevation = CardDefaults.cardElevation(defaultElevation = 1.dp)
                                        ) {
                                            Row(
                                                modifier = Modifier.padding(3.dp)
                                            ) {
                                                // 无冲突标签
                                                Surface(
                                                    onClick = { selectedTabIndex = 0 },
                                                    modifier = Modifier
                                                        .weight(1f)
                                                        .height(24.dp),
                                                    shape = RoundedCornerShape(12.dp),
                                                    color = if (selectedTabIndex == 0) {
                                                        MaterialTheme.colorScheme.primary
                                                    } else {
                                                        Color.Transparent
                                                    }
                                                ) {
                                                    Box(
                                                        modifier = Modifier.fillMaxSize(),
                                                        contentAlignment = Alignment.Center
                                                    ) {
                                                        Text(
                                                            text = "无冲突 ($noConflictCount)",
                                                            fontSize = 10.sp,
                                                            fontWeight = FontWeight.Medium,
                                                            color = if (selectedTabIndex == 0) {
                                                                Color.White
                                                            } else {
                                                                MaterialTheme.colorScheme.primary
                                                            }
                                                        )
                                                    }
                                                }
                                                
                                                Spacer(modifier = Modifier.width(3.dp))
                                                
                                                // 有冲突标签
                                                Surface(
                                                    onClick = { selectedTabIndex = 1 },
                                                    modifier = Modifier
                                                        .weight(1f)
                                                        .height(24.dp),
                                                    shape = RoundedCornerShape(12.dp),
                                                    color = if (selectedTabIndex == 1) {
                                                        MaterialTheme.colorScheme.primary
                                                    } else {
                                                        Color.Transparent
                                                    }
                                                ) {
                                                    Box(
                                                        modifier = Modifier.fillMaxSize(),
                                                        contentAlignment = Alignment.Center
                                                    ) {
                                                        Text(
                                                            text = "有冲突 ($conflictCount)",
                                                            fontSize = 10.sp,
                                                            fontWeight = FontWeight.Medium,
                                                            color = if (selectedTabIndex == 1) {
                                                                Color.White
                                                            } else {
                                                                MaterialTheme.colorScheme.primary
                                                            }
                                                        )
                                                    }
                                                }
                                            }
                                        }
                                        
                                        // 根据tab状态显示不同的菜谱列表（使用已过滤的展示列表）
                                        val recipesToShow = when (selectedTabIndex) {
                                            0 -> displayNoConflictRecipes
                                            1 -> displayConflictRecipes
                                            else -> displayAllRecipes
                                        }
                                        
                                        // 该符文下的菜谱
                                        recipesToShow.forEach { recipe ->
                                            Card(
                            modifier = Modifier
                                .fillMaxWidth()
                                                    .padding(horizontal = 8.dp, vertical = 2.dp)
                                                    .clickable { onRecipeSelected(recipe) },
                                                elevation = CardDefaults.cardElevation(defaultElevation = 1.dp)
                                            ) {
                                Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                        .padding(12.dp)
                                ) {
                                    // 主要内容区域
                                    Column {
                                        // 第一行：菜谱名字 + 星级 + 时间 + 来源（右对齐）
                                        Row(
                                            modifier = Modifier.fillMaxWidth(),
                                            verticalAlignment = Alignment.CenterVertically,
                                            horizontalArrangement = Arrangement.SpaceBetween
                            ) {
                                            // 左侧：菜谱名字 + 星级 + 时间
                                Row(
                                    verticalAlignment = Alignment.CenterVertically
                                ) {
                                    Text(
                                        text = recipe.name,
                                        fontSize = 14.sp,
                                        fontWeight = FontWeight.Medium
                                    )

                                    Spacer(modifier = Modifier.width(8.dp))

                                                // 星级显示（火焰格式）
                                                val starText = when (recipe.rarity) {
                                                    1 -> "一🔥"
                                                    2 -> "二🔥"
                                                    3 -> "三🔥"
                                                    4 -> "四🔥"
                                                    5 -> "五🔥"
                                                    else -> "${recipe.rarity}🔥"
                                                }
                                                Text(
                                                    text = starText,
                                                    fontSize = 12.sp,
                                                    color = MaterialTheme.colorScheme.primary,
                                                    fontWeight = FontWeight.Medium
                                                )
                                                
                                                Spacer(modifier = Modifier.width(8.dp))
                                                
                                                // 时间显示（秒转换为分:秒格式）
                                                val minutes = recipe.time / 60
                                                val seconds = recipe.time % 60
                                                val timeText = if (minutes > 0) {
                                                    "${minutes}分${seconds}秒"
                                                } else {
                                                    "${seconds}秒"
                                                }
                                                Text(
                                                    text = timeText,
                                                    fontSize = 11.sp,
                                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                                )
                                }
                                
                                            // 右侧：来源（参考厨师选择页面的格式）
                                Text(
                                                text = "来源: ${recipe.origin.replace("<br>", "、")}",
                                                fontSize = 8.sp,
                                                color = MaterialTheme.colorScheme.onSurfaceVariant,
                                                maxLines = 2,
                                                lineHeight = 9.sp,
                                                modifier = Modifier.weight(1f),
                                                textAlign = TextAlign.End
                                            )
                                        }

                                        // 第二行：技法值（左对齐）+ 拥有状态和品级（右对齐）
                                        Row(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .padding(top = 4.dp),
                                            horizontalArrangement = Arrangement.SpaceBetween,
                                            verticalAlignment = Alignment.CenterVertically
                                        ) {
                                            // 技法值和符文（左对齐）
                                            Row(
                                                verticalAlignment = Alignment.CenterVertically,
                                                horizontalArrangement = Arrangement.spacedBy(8.dp)
                                            ) {
                                                // 技法值
                                                val chefIndex = selectedRecipeSlotIndex / 3 // 计算对应的厨师索引
                                                val chef = selectedChefs.getOrNull(chefIndex)
                                                val equip = selectedEquips.getOrNull(chefIndex)
                                                
                                                // 始终显示菜谱技法需求，不计算神差值
                                                val skillText = getRecipeSkillText(recipe)
                                                if (skillText.isNotEmpty()) {
                                                    Text(
                                                        text = skillText,
                                                        fontSize = 11.sp,
                                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                                    )
                                                }

                                                // 符文字段 - 通过贵客礼物获取符文信息
                                                val runeName = remember(recipe.name, gameData) {
                                                    gameData?.guests?.flatMap { guest ->
                                                        guest.gifts.filter { gift ->
                                                            gift.recipe == recipe.name
                                                        }.map { gift ->
                                                            gift.antique
                                                        }
                                                    }?.firstOrNull() ?: ""
                                                }
                                                
                                                // 判断是否为双贵客菜谱
                                                val guestCount = remember(recipe.name, gameData) {
                                                    gameData?.guests?.count { guest ->
                                                        guest.gifts.any { gift -> 
                                                            gift.recipe == recipe.name 
                                                        }
                                                    } ?: 1
                                                }
                                                val isDualGuestRecipe = guestCount >= 2
                                                
                                                if (runeName.isNotEmpty()) {
                                                    Row(
                                                        verticalAlignment = Alignment.CenterVertically,
                                                        horizontalArrangement = Arrangement.spacedBy(4.dp)
                                                    ) {
                                                        Text(
                                                            text = "符文: $runeName",
                                                            fontSize = 10.sp,
                                                            color = MaterialTheme.colorScheme.tertiary,
                                                            fontWeight = FontWeight.Medium
                                                        )
                                                        
                                                        // 如果是双贵客菜谱，显示红色标记
                                                        if (isDualGuestRecipe) {
                                                            Text(
                                                                text = "双贵客",
                                                                fontSize = 8.sp,
                                                                color = Color.Red,
                                                                fontWeight = FontWeight.Bold
                                                            )
                                                        }
                                                    }
                                                } else {
                                                    // 显示无符文
                                                    Text(
                                                        text = "符文: 无",
                                                        fontSize = 10.sp,
                                                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                                                        fontWeight = FontWeight.Normal
                                                    )
                                                }
                                            }

                                            Spacer(modifier = Modifier.weight(1f))

                                            // 右侧：品级和拥有状态
                                            Row(
                                                verticalAlignment = Alignment.CenterVertically,
                                                horizontalArrangement = Arrangement.spacedBy(8.dp)
                                            ) {
                                                // 品级显示（如果有选中的厨师）
                                                val chefIndex = selectedRecipeSlotIndex / 3 // 计算对应的厨师索引
                                                val chef = selectedChefs.getOrNull(chefIndex)
                                                val equip = selectedEquips.getOrNull(chefIndex)

                                                if (chef != null) {
                                                    // 应用技法加成（包含厨师间技法影响）
                                                    val enhancedChef = com.example.show_auto.utils.ChefSkillCalculator.applyAllSkills(
                                                        chef, ultimateSkills, equip, skills, chefInteractions.getOrNull(chefIndex)
                                                    )
                                                    
                                                    // 如果启用厨具遗玉，还需要应用心法盘技法值加成
                                                    val finalEnhancedChef = if (gameData != null && chefIndex < chefAmbers.size) {
                                                        // 使用传入的心法盘配置和等级
                                                        val chefAmbersForChef = chefAmbers.getOrNull(chefIndex) ?: listOf(null, null, null)
                                                        val chefLevel = chefLevels.getOrNull(chefIndex) ?: 1
                                                        
                                                        // 如果开启了心法盘默认满级，则对所有蓝色心法盘位置使用满朋陨
                                                        val finalAmbers = if (defaultMaxLevelAmber) {
                                                            applyMaxLevelAmberToBluePositions(chef, chefAmbersForChef.toMutableList(), gameData, true)
                                                        } else {
                                                            chefAmbersForChef
                                                        }
                                                        
                                                        // 计算心法盘技法值加成
                                                        val techniqueValuesWithAmbers = calculateTechniqueValuesWithAmbers(chef, skills, gameData, chefLevel, finalAmbers, enhancedChef)
                                                        
                                                        // 创建包含心法盘加成的最终厨师数据
                                                        enhancedChef.copy(
                                                            stirfry = techniqueValuesWithAmbers["stirfry"]?.second ?: enhancedChef.stirfry,
                                                            boil = techniqueValuesWithAmbers["boil"]?.second ?: enhancedChef.boil,
                                                            knife = techniqueValuesWithAmbers["knife"]?.second ?: enhancedChef.knife,
                                                            fry = techniqueValuesWithAmbers["fry"]?.second ?: enhancedChef.fry,
                                                            bake = techniqueValuesWithAmbers["bake"]?.second ?: enhancedChef.bake,
                                                            steam = techniqueValuesWithAmbers["steam"]?.second ?: enhancedChef.steam
                                                        )
                                                    } else {
                                                        enhancedChef
                                                    }

                                                    val rank = com.example.show_auto.utils.RecipeRankCalculator.calculateRecipeRank(finalEnhancedChef, recipe)

                                                    // 显示品级
                                                    val rankText = com.example.show_auto.utils.RecipeRankCalculator.getRankShortText(rank)
                                                    val rankColor = com.example.show_auto.utils.RecipeRankCalculator.getRankColor(rank)

                                                    Text(
                                                        text = rankText,
                                                        fontSize = 10.sp,
                                                        color = Color(rankColor),
                                                        fontWeight = FontWeight.Bold
                                                    )
                                                }

                                                // 拥有状态
                                                Text(
                                                    text = if (recipe.got) "已拥有" else "未拥有",
                                                    fontSize = 10.sp,
                                                    color = if (recipe.got)
                                                        MaterialTheme.colorScheme.primary
                                                    else
                                                        Color.Red
                                                )
                                            }
                                        }
                                    }
                                }
                            }
                                        }
                                    }
                                }
                            }
                        }
                        // 添加闭合大括号来配合折叠逻辑
                        }
                    }
                }
            }
        },
        confirmButton = {
            Row {
                if (searchText.isNotEmpty()) {
                    TextButton(onClick = { searchText = "" }) {
                        Text("清空搜索")
                    }
                }
                TextButton(onClick = {
                    onClearCurrentRecipe() // 只清空当前选择框的菜谱数据
                    onDismiss() // 关闭对话框
                }) {
                    Text("清空当前")
                }
            TextButton(onClick = onDismiss) {
                    Text("关闭")
                }
            }
        }
    )
}

@Composable
private fun RuneSettingsDialog(
    settingsStorage: SettingsStorage,
    onDismiss: () -> Unit
) {
    // Tab切换状态：0=金符文，1=银符文，2=铜符文
    var selectedTabIndex by remember { mutableStateOf(0) }
    
    // 心法盘默认满级设置状态
    var defaultMaxLevelAmber by remember { mutableStateOf(settingsStorage.getCalculatorDefaultMaxLevelAmber()) }
    // 默认全修炼设置状态
    var defaultAllUltimate by remember { mutableStateOf(settingsStorage.getCalculatorDefaultAllUltimate()) }
    // 使用个人数据设置状态
    var usePersonalData by remember { mutableStateOf(settingsStorage.getCalculatorUsePersonalData()) }
    // 使用全部厨师设置状态
    var useAllChefs by remember { mutableStateOf(settingsStorage.getCalculatorUseAllChefs()) }
    
    // 实时读取设置状态，确保开关变化时立即生效
    LaunchedEffect(Unit) {
        while (true) {
            kotlinx.coroutines.delay(100) // 每100ms检查一次
            val newMaxLevelSetting = settingsStorage.getCalculatorDefaultMaxLevelAmber()
            if (newMaxLevelSetting != defaultMaxLevelAmber) {
                defaultMaxLevelAmber = newMaxLevelSetting
            }
            val newAllUltimateSetting = settingsStorage.getCalculatorDefaultAllUltimate()
            if (newAllUltimateSetting != defaultAllUltimate) {
                defaultAllUltimate = newAllUltimateSetting
            }
            // 同时监听使用个人数据设置变化
            val newUsePersonalData = settingsStorage.getCalculatorUsePersonalData()
            if (newUsePersonalData != usePersonalData) {
                usePersonalData = newUsePersonalData
            }
            // 同时监听使用全部厨师设置变化
            val newUseAllChefs = settingsStorage.getCalculatorUseAllChefs()
            if (newUseAllChefs != useAllChefs) {
                useAllChefs = newUseAllChefs
            }
        }
    }
    
    // 符文分类定义
    val goldRunes = remember {
        listOf("恐怖利刃", "鼓风机", "蒸馏杯", "千年煮鳖", "香烤鱼排", "五星炒果")
    }
    val silverRunes = remember {
        listOf("刀嘴鹦鹉", "一昧真火", "蒸汽宝石", "耐煮的水草", "焦虫", "暖石")
    }
    val bronzeRunes = remember {
        listOf("剪刀蟹", "油火虫", "蒸汽耳环", "防水的柠檬", "烤焦的菊花", "五香果")
    }
    

    
    // 符文选择状态 - 从持久化存储初始化
    var selectedGoldRunes by remember { 
        mutableStateOf(settingsStorage.getGoldRuneSelections()) 
    }
    var selectedSilverRunes by remember { 
        mutableStateOf(settingsStorage.getSilverRuneSelections()) 
    }
    var selectedBronzeRunes by remember { 
        mutableStateOf(settingsStorage.getBronzeRuneSelections()) 
    }
    
    // 弹窗提示状态
    var showTypeConflictDialog by remember { mutableStateOf(false) }
    var conflictMessage by remember { mutableStateOf("") }
    
    // 贵客必来份数对照表弹窗状态
    var showGuestPortionTable by remember { mutableStateOf(false) }
    
    // 初始化符文选择状态
    LaunchedEffect(Unit) {
        // 从持久化存储重新读取所有数据，确保数据是最新的
        val savedGoldSelections = settingsStorage.getGoldRuneSelections()
        val savedSilverSelections = settingsStorage.getSilverRuneSelections()
        val savedBronzeSelections = settingsStorage.getBronzeRuneSelections()
        
        // 更新选择状态
        selectedGoldRunes = savedGoldSelections
        selectedSilverRunes = savedSilverSelections
        selectedBronzeRunes = savedBronzeSelections
    }
    

    
    // 检查符文类型冲突
    fun checkRuneTypeConflict(newRune: String, newRuneType: String): Boolean {
        val hasGoldRunes = selectedGoldRunes.isNotEmpty()
        val hasSilverRunes = selectedSilverRunes.isNotEmpty()
        val hasBronzeRunes = selectedBronzeRunes.isNotEmpty()
        
        // 如果新符文是金符文
        if (newRuneType == "gold") {
            if (hasSilverRunes || hasBronzeRunes) {
                conflictMessage = "只能同时查询一类符文"
                return true
            }
        }
        // 如果新符文是银符文
        else if (newRuneType == "silver") {
            if (hasGoldRunes || hasBronzeRunes) {
                conflictMessage = "只能同时查询一类符文"
                return true
            }
        }
        // 如果新符文是铜符文
        else if (newRuneType == "bronze") {
            if (hasGoldRunes || hasSilverRunes) {
                conflictMessage = "只能同时查询一类符文"
                return true
            }
        }
        
        return false
    }
    


    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "查询设置",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold
                )
                
                // 贵客必来份数对照表按钮
                Button(
                    onClick = { showGuestPortionTable = true },
                    modifier = Modifier.height(32.dp),
                    shape = RoundedCornerShape(6.dp),
                    contentPadding = PaddingValues(horizontal = 12.dp, vertical = 4.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.primary
                    )
                ) {
                    Text(
                        text = "贵客必来对照表",
                        fontSize = 12.sp,
                        color = MaterialTheme.colorScheme.onPrimary,
                        fontWeight = FontWeight.Medium
                    )
                }
            }
        },
        text = {
            LazyColumn(
                modifier = Modifier
                    .fillMaxWidth()
                    .heightIn(max = 600.dp)
            ) {
                item {
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                    ) {
                // 设置选项行
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 12.dp),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    // 心法盘默认满级设置
                    Card(
                        modifier = Modifier.weight(1f),
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.surfaceVariant
                        ),
                        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
                    ) {
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(6.dp),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(
                                text = "心法盘默认满级",
                                fontSize = 10.sp,
                                fontWeight = FontWeight.Medium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                            
                            CustomSwitch(
                                checked = defaultMaxLevelAmber,
                                onCheckedChange = { enabled ->
                                    defaultMaxLevelAmber = enabled
                                    settingsStorage.saveCalculatorDefaultMaxLevelAmber(enabled)
                                },
                                modifier = Modifier.size(40.dp, 20.dp)
                            )
                        }
                    }
                    
                    // 默认全修炼设置
                    Card(
                        modifier = Modifier.weight(1f),
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.surfaceVariant
                        ),
                        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
                    ) {
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(6.dp),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(
                                text = "默认全修炼",
                                fontSize = 10.sp,
                                fontWeight = FontWeight.Medium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                            
                            CustomSwitch(
                                checked = defaultAllUltimate,
                                onCheckedChange = { enabled ->
                                    defaultAllUltimate = enabled
                                    settingsStorage.saveCalculatorDefaultAllUltimate(enabled)
                                },
                                modifier = Modifier.size(40.dp, 20.dp)
                            )
                        }
                    }
                }
                
                // 新增配置行
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 12.dp),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    // 使用个人数据设置
                    Card(
                        modifier = Modifier.weight(1f),
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.surfaceVariant
                        ),
                        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
                    ) {
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(6.dp),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(
                                text = "启用厨具遗玉",
                                fontSize = 10.sp,
                                fontWeight = FontWeight.Medium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                            
                            CustomSwitch(
                                checked = usePersonalData,
                                onCheckedChange = { enabled ->
                                    usePersonalData = enabled
                                    settingsStorage.saveCalculatorUsePersonalData(enabled)
                                },
                                modifier = Modifier.size(40.dp, 20.dp)
                            )
                        }
                    }
                    
                    // 使用全部厨师设置
                    Card(
                        modifier = Modifier.weight(1f),
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.surfaceVariant
                        ),
                        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
                    ) {
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(6.dp),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(
                                text = "使用全部厨师",
                                fontSize = 10.sp,
                                fontWeight = FontWeight.Medium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                            
                            CustomSwitch(
                                checked = useAllChefs,
                                onCheckedChange = { enabled ->
                                    useAllChefs = enabled
                                    settingsStorage.saveCalculatorUseAllChefs(enabled)
                                },
                                modifier = Modifier.size(40.dp, 20.dp)
                            )
                        }
                    }
                }
                
                // 制作时间配置行
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 12.dp),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    // 制作时间输入框配置
                    Card(
                        modifier = Modifier.weight(1f),
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.surfaceVariant
                        ),
                        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
                    ) {
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(6.dp),
                            horizontalArrangement = Arrangement.Start,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(
                                text = "制作时间",
                                fontSize = 10.sp,
                                fontWeight = FontWeight.Medium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                            
                            Spacer(modifier = Modifier.width(8.dp))
                            
                            // 制作时间输入框 - 支持小数点输入
                            var timeInputText by remember { 
                                mutableStateOf(
                                    try {
                                        settingsStorage.getCalculatorDefaultTime().toString()
                                    } catch (e: Exception) {
                                        // 如果出现异常，使用默认值
                                        "7.0"
                                    }
                                ) 
                            }
                            var timeFocusRequester by remember { mutableStateOf(FocusRequester()) }
                            var timeCursorVisible by remember { mutableStateOf(false) }
                            var timeLastInputTime by remember { mutableStateOf(0L) }
                            var timeInputFieldEnabled by remember { mutableStateOf(true) }
                            
                            // 2秒后自动隐藏光标
                            LaunchedEffect(timeLastInputTime) {
                                if (timeLastInputTime > 0) {
                                    delay(2000) // 2秒延迟
                                    timeCursorVisible = false
                                    // 失去焦点以隐藏选择指示器
                                    timeFocusRequester.freeFocus()
                                    // 暂时禁用输入框来清除选择状态
                                    timeInputFieldEnabled = false
                                    delay(50) // 短暂延迟
                                    timeInputFieldEnabled = true
                                }
                            }
                            
                            // 数字输入框 - 支持小数点
                            Box(
                                modifier = Modifier
                                    .width(40.dp) // 增加宽度以适应小数点
                                    .height(20.dp)
                                    .border(
                                        width = 1.dp,
                                        color = MaterialTheme.colorScheme.outline,
                                        shape = RoundedCornerShape(2.dp)
                                    )
                                    .background(
                                        color = MaterialTheme.colorScheme.surface,
                                        shape = RoundedCornerShape(2.dp)
                                    )
                                    .clickable(
                                        interactionSource = remember { MutableInteractionSource() },
                                        indication = null
                                    ) {
                                        // 点击输入框时聚焦
                                        timeFocusRequester.requestFocus()
                                    },
                                contentAlignment = Alignment.Center
                            ) {
                                BasicTextField(
                                    value = timeInputText,
                                    enabled = timeInputFieldEnabled,
                                    onValueChange = { newValue ->
                                        // 允许数字和小数点，但限制只能有一个小数点
                                        val filteredValue = newValue.filter { it.isDigit() || it == '.' }
                                        // 确保只有一个小数点
                                        val dotCount = filteredValue.count { it == '.' }
                                        val finalValue = if (dotCount > 1) {
                                            // 如果有多个小数点，只保留第一个
                                            val firstDotIndex = filteredValue.indexOf('.')
                                            filteredValue.substring(0, firstDotIndex + 1) + filteredValue.substring(firstDotIndex + 1).filter { it.isDigit() }
                                        } else {
                                            filteredValue
                                        }
                                        
                                        timeInputText = finalValue
                                        
                                        // 更新最后输入时间，显示光标
                                        timeLastInputTime = System.currentTimeMillis()
                                        timeCursorVisible = true
                                        
                                        if (finalValue.isNotEmpty()) {
                                            val floatValue = finalValue.toFloatOrNull()
                                            if (floatValue != null) {
                                                // 限制最大值为24，最小值为0
                                                if (floatValue > 24.0f) {
                                                    val maxTime = 24.0f
                                                    settingsStorage.saveCalculatorDefaultTime(maxTime)
                                                    timeInputText = "24.0"
                                                } else if (floatValue < 0.0f) {
                                                    val minTime = 0.0f
                                                    settingsStorage.saveCalculatorDefaultTime(minTime)
                                                    timeInputText = "0.0"
                                                } else {
                                                    settingsStorage.saveCalculatorDefaultTime(floatValue)
                                                }
                                            }
                                        }
                                    },
                                    textStyle = androidx.compose.ui.text.TextStyle(
                                        fontSize = 10.sp,
                                        fontWeight = FontWeight.Medium,
                                        color = MaterialTheme.colorScheme.onSurface,
                                        textAlign = TextAlign.Center,
                                        lineHeight = 10.sp
                                    ),
                                    singleLine = true,
                                    modifier = Modifier
                                        .fillMaxSize()
                                        .focusRequester(timeFocusRequester)
                                        .onFocusChanged { focusState ->
                                            // 获得焦点时显示光标
                                            if (focusState.isFocused) {
                                                timeCursorVisible = true
                                                timeLastInputTime = System.currentTimeMillis()
                                            }
                                            // 失去焦点时处理输入值
                                            if (!focusState.isFocused) {
                                                if (timeInputText.isEmpty() || timeInputText.toFloatOrNull() == null) {
                                                    // 如果输入为空或无效，重置为当前值
                                                    timeInputText = settingsStorage.getCalculatorDefaultTime().toString()
                                                } else {
                                                    val floatValue = timeInputText.toFloatOrNull() ?: 0.0f
                                                    if (floatValue > 24.0f) {
                                                        val maxTime = 24.0f
                                                        settingsStorage.saveCalculatorDefaultTime(maxTime)
                                                        timeInputText = "24.0"
                                                    } else if (floatValue < 0.0f) {
                                                        val minTime = 0.0f
                                                        settingsStorage.saveCalculatorDefaultTime(minTime)
                                                        timeInputText = "0.0"
                                                    } else {
                                                        // 确保存储值与输入框同步
                                                        settingsStorage.saveCalculatorDefaultTime(floatValue)
                                                    }
                                                }
                                            }
                                        },
                                    cursorBrush = if (timeCursorVisible) SolidColor(MaterialTheme.colorScheme.primary) else SolidColor(Color.Transparent)
                                ) { innerTextField ->
                                    Box(
                                        modifier = Modifier.fillMaxSize(),
                                        contentAlignment = Alignment.Center
                                    ) {
                                        innerTextField()
                                    }
                                }
                            }
                            
                            Spacer(modifier = Modifier.width(4.dp))
                            
                            // 小时单位
                            Text(
                                text = "小时",
                                fontSize = 10.sp,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                            
                            // 同步输入框和存储值
                            LaunchedEffect(Unit) {
                                val storedTime = settingsStorage.getCalculatorDefaultTime()
                                if (timeInputText != storedTime.toString()) {
                                    timeInputText = storedTime.toString()
                                }
                            }
                        }
                    }
                    
                    // 查询开关配置
                    Card(
                        modifier = Modifier.weight(1f),
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.surfaceVariant
                        ),
                        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
                    ) {
                        // 使用本地状态来管理开关状态，确保UI实时更新
                        var localQueryMode by remember { mutableStateOf(settingsStorage.getCalculatorQueryMode()) }
                        
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(6.dp),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(
                                text = if (localQueryMode) "查询效率" else "查询必来",
                                fontSize = 10.sp,
                                fontWeight = FontWeight.Medium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                            
                            // 使用CustomSwitch组件，始终显示开启状态
                            CustomSwitch(
                                checked = localQueryMode,
                                onCheckedChange = { enabled ->
                                    localQueryMode = enabled
                                    settingsStorage.saveCalculatorQueryMode(enabled)
                                },
                                modifier = Modifier.size(40.dp, 20.dp),
                                alwaysOn = true // 始终显示开启状态
                            )
                        }
                    }
                }
                
                // 金符文选择卡片
                var isGoldRuneExpanded by remember { mutableStateOf(settingsStorage.getGoldRuneExpanded()) }
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 16.dp)
                        .clickable { 
                            isGoldRuneExpanded = !isGoldRuneExpanded
                            // 保存展开状态到持久化存储
                            settingsStorage.saveGoldRuneExpanded(isGoldRuneExpanded)
                        },
                    colors = CardDefaults.cardColors(
                        containerColor = MaterialTheme.colorScheme.surfaceVariant
                    ),
                    elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
                ) {
                    Column(
                        modifier = Modifier.padding(12.dp)
                    ) {
                        // 卡片标题和展开按钮
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(
                                text = "金符文",
                                fontSize = 14.sp,
                                fontWeight = FontWeight.Medium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                            
                            Icon(
                                imageVector = if (isGoldRuneExpanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
                                contentDescription = if (isGoldRuneExpanded) "收起" else "展开",
                                tint = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                        
                        // 展开后的符文列表
                        if (isGoldRuneExpanded) {
                            Spacer(modifier = Modifier.height(12.dp))
                            

                            
                            // 符文卡片布局 - 每行两个
                            LazyColumn(
                                modifier = Modifier.heightIn(max = 200.dp),
                                verticalArrangement = Arrangement.spacedBy(8.dp)
                            ) {
                                val runeRows = goldRunes.chunked(2)
                                items(runeRows) { runeRow ->
                                    Row(
                                        modifier = Modifier.fillMaxWidth(),
                                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                                    ) {
                                        runeRow.forEach { rune ->
                                            RuneCard(
                                                rune = rune,
                                                isSelected = selectedGoldRunes.contains(rune),
                                                onToggle = {
                                                    if (selectedGoldRunes.contains(rune)) {
                                                        // 取消选择
                                                        selectedGoldRunes = selectedGoldRunes - rune
                                                        // 保存到持久化存储
                                                        settingsStorage.saveGoldRuneSelections(selectedGoldRunes)
                                                    } else {
                                                        // 尝试选择新符文
                                                        if (checkRuneTypeConflict(rune, "gold")) {
                                                            showTypeConflictDialog = true
                                                        } else {
                                                            selectedGoldRunes = selectedGoldRunes + rune
                                                            // 保存到持久化存储
                                                            settingsStorage.saveGoldRuneSelections(selectedGoldRunes)
                                                        }
                                                    }
                                                },
                                                modifier = Modifier.weight(1f)
                                            )
                                        }
                                        // 如果这一行只有一个符文，添加空白占位符
                                        if (runeRow.size == 1) {
                                            Spacer(modifier = Modifier.weight(1f))
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                
                // 银符文选择卡片
                var isSilverRuneExpanded by remember { mutableStateOf(settingsStorage.getSilverRuneExpanded()) }
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 16.dp)
                        .clickable { 
                            isSilverRuneExpanded = !isSilverRuneExpanded
                            // 保存展开状态到持久化存储
                            settingsStorage.saveSilverRuneExpanded(isSilverRuneExpanded)
                        },
                    colors = CardDefaults.cardColors(
                        containerColor = MaterialTheme.colorScheme.surfaceVariant
                    ),
                    elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
                ) {
                    Column(
                        modifier = Modifier.padding(12.dp)
                    ) {
                        // 卡片标题和展开按钮
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(
                                text = "银符文",
                                fontSize = 14.sp,
                                fontWeight = FontWeight.Medium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                            
                            Icon(
                                imageVector = if (isSilverRuneExpanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
                                contentDescription = if (isSilverRuneExpanded) "收起" else "展开",
                                tint = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                        
                        // 展开后的符文列表
                        if (isSilverRuneExpanded) {
                            Spacer(modifier = Modifier.height(12.dp))
                            

                            
                            // 符文卡片布局 - 每行两个
                            LazyColumn(
                                modifier = Modifier.heightIn(max = 200.dp),
                                verticalArrangement = Arrangement.spacedBy(8.dp)
                            ) {
                                val runeRows = silverRunes.chunked(2)
                                items(runeRows) { runeRow ->
                                    Row(
                                        modifier = Modifier.fillMaxWidth(),
                                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                                    ) {
                                        runeRow.forEach { rune ->
                                            RuneCard(
                                                rune = rune,
                                                isSelected = selectedSilverRunes.contains(rune),
                                                onToggle = {
                                                    if (selectedSilverRunes.contains(rune)) {
                                                        // 取消选择
                                                        selectedSilverRunes = selectedSilverRunes - rune
                                                        // 保存到持久化存储
                                                        settingsStorage.saveSilverRuneSelections(selectedSilverRunes)
                                                    } else {
                                                        // 尝试选择新符文
                                                        if (checkRuneTypeConflict(rune, "silver")) {
                                                            showTypeConflictDialog = true
                                                        } else {
                                                            selectedSilverRunes = selectedSilverRunes + rune
                                                            // 保存到持久化存储
                                                            settingsStorage.saveSilverRuneSelections(selectedSilverRunes)
                                                        }
                                                    }
                                                },
                                                modifier = Modifier.weight(1f)
                                            )
                                        }
                                        // 如果这一行只有一个符文，添加空白占位符
                                        if (runeRow.size == 1) {
                                            Spacer(modifier = Modifier.weight(1f))
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                
                // 铜符文选择卡片
                var isBronzeRuneExpanded by remember { mutableStateOf(settingsStorage.getBronzeRuneExpanded()) }
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 16.dp)
                        .clickable { 
                            isBronzeRuneExpanded = !isBronzeRuneExpanded
                            // 保存展开状态到持久化存储
                            settingsStorage.saveBronzeRuneExpanded(isBronzeRuneExpanded)
                        },
                    colors = CardDefaults.cardColors(
                        containerColor = MaterialTheme.colorScheme.surfaceVariant
                    ),
                    elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
                ) {
                    Column(
                        modifier = Modifier.padding(12.dp)
                    ) {
                        // 卡片标题和展开按钮
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(
                                text = "铜符文",
                                fontSize = 14.sp,
                                fontWeight = FontWeight.Medium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                            
                            Icon(
                                imageVector = if (isBronzeRuneExpanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
                                contentDescription = if (isBronzeRuneExpanded) "收起" else "展开",
                                tint = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                        
                        // 展开后的符文列表
                        if (isBronzeRuneExpanded) {
                            Spacer(modifier = Modifier.height(12.dp))
                            

                            
                            // 符文卡片布局 - 每行两个
                            LazyColumn(
                                modifier = Modifier.heightIn(max = 200.dp),
                                verticalArrangement = Arrangement.spacedBy(8.dp)
                            ) {
                                val runeRows = bronzeRunes.chunked(2)
                                items(runeRows) { runeRow ->
                                    Row(
                                        modifier = Modifier.fillMaxWidth(),
                                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                                    ) {
                                        runeRow.forEach { rune ->
                                            RuneCard(
                                                rune = rune,
                                                isSelected = selectedBronzeRunes.contains(rune),
                                                onToggle = {
                                                    if (selectedBronzeRunes.contains(rune)) {
                                                        // 取消选择
                                                        selectedBronzeRunes = selectedBronzeRunes - rune
                                                        // 保存到持久化存储
                                                        settingsStorage.saveBronzeRuneSelections(selectedBronzeRunes)
                                                    } else {
                                                        // 尝试选择新符文
                                                        if (checkRuneTypeConflict(rune, "bronze")) {
                                                            showTypeConflictDialog = true
                                                        } else {
                                                            selectedBronzeRunes = selectedBronzeRunes + rune
                                                            // 保存到持久化存储
                                                            settingsStorage.saveBronzeRuneSelections(selectedBronzeRunes)
                                                        }
                                                    }
                                                },
                                                modifier = Modifier.weight(1f)
                                            )
                                        }
                                        // 如果这一行只有一个符文，添加空白占位符
                                        if (runeRow.size == 1) {
                                            Spacer(modifier = Modifier.weight(1f))
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                    }
                }
            }
        },
        confirmButton = {
            TextButton(onClick = onDismiss) {
                Text("确定")
            }
        }
    )
    
    // 符文类型冲突提示弹窗
    if (showTypeConflictDialog) {
        SaveSuccessDialog(
            message = conflictMessage,
            onDismiss = { showTypeConflictDialog = false }
        )
    }
    
    // 贵客必来份数对照表弹窗
    if (showGuestPortionTable) {
        GuestPortionTableDialog(
            onDismiss = { showGuestPortionTable = false }
        )
    }
    

}

/**
 * 贵客必来份数对照表弹窗
 */
@Composable
private fun GuestPortionTableDialog(
    onDismiss: () -> Unit
) {
    // 贵客率-份数对照表数据（完整的1-5星菜谱数据）
    val guestPortionTable = remember {
        mapOf(
            // 贵客率从80%到540%，对应1-5星菜谱的份数
            80 to mapOf(1 to 59, 2 to 39, 3 to 42, 4 to 91, 5 to 62),
            90 to mapOf(1 to 57, 2 to 38, 3 to 40, 4 to 86, 5 to 59),
            100 to mapOf(1 to 55, 2 to 36, 3 to 39, 4 to 81, 5 to 56),
            110 to mapOf(1 to 53, 2 to 35, 3 to 37, 4 to 77, 5 to 53),
            120 to mapOf(1 to 52, 2 to 34, 3 to 36, 4 to 73, 5 to 50),
            130 to mapOf(1 to 50, 2 to 33, 3 to 34, 4 to 69, 5 to 48),
            140 to mapOf(1 to 49, 2 to 32, 3 to 33, 4 to 66, 5 to 46),
            150 to mapOf(1 to 47, 2 to 31, 3 to 32, 4 to 63, 5 to 44),
            160 to mapOf(1 to 46, 2 to 31, 3 to 31, 4 to 60, 5 to 42),
            170 to mapOf(1 to 45, 2 to 30, 3 to 30, 4 to 57, 5 to 40),
            180 to mapOf(1 to 44, 2 to 29, 3 to 30, 4 to 55, 5 to 38),
            190 to mapOf(1 to 43, 2 to 29, 3 to 29, 4 to 52, 5 to 37),
            200 to mapOf(1 to 42, 2 to 28, 3 to 28, 4 to 50, 5 to 36),
            210 to mapOf(1 to 41, 2 to 28, 3 to 27, 4 to 48, 5 to 34),
            220 to mapOf(1 to 41, 2 to 27, 3 to 27, 4 to 46, 5 to 33),
            230 to mapOf(1 to 40, 2 to 27, 3 to 26, 4 to 45, 5 to 32),
            240 to mapOf(1 to 39, 2 to 26, 3 to 26, 4 to 43, 5 to 31),
            250 to mapOf(1 to 39, 2 to 26, 3 to 25, 4 to 41, 5 to 30),
            260 to mapOf(1 to 38, 2 to 25, 3 to 25, 4 to 40, 5 to 29),
            270 to mapOf(1 to 37, 2 to 25, 3 to 24, 4 to 39, 5 to 28),
            280 to mapOf(1 to 37, 2 to 25, 3 to 24, 4 to 37, 5 to 27),
            290 to mapOf(1 to 36, 2 to 24, 3 to 23, 4 to 36, 5 to 26),
            300 to mapOf(1 to 36, 2 to 24, 3 to 23, 4 to 35, 5 to 25),
            310 to mapOf(1 to 35, 2 to 24, 3 to 23, 4 to 34, 5 to 25),
            320 to mapOf(1 to 35, 2 to 23, 3 to 22, 4 to 33, 5 to 24),
            330 to mapOf(1 to 35, 2 to 23, 3 to 22, 4 to 32, 5 to 23),
            340 to mapOf(1 to 34, 2 to 23, 3 to 22, 4 to 31, 5 to 23),
            350 to mapOf(1 to 34, 2 to 23, 3 to 21, 4 to 30, 5 to 22),
            360 to mapOf(1 to 33, 2 to 22, 3 to 21, 4 to 29, 5 to 22),
            370 to mapOf(1 to 33, 2 to 22, 3 to 21, 4 to 28, 5 to 21),
            380 to mapOf(1 to 33, 2 to 22, 3 to 20, 4 to 27, 5 to 20),
            390 to mapOf(1 to 32, 2 to 22, 3 to 20, 4 to 26, 5 to 20),
            400 to mapOf(1 to 32, 2 to 21, 3 to 20, 4 to 26, 5 to 19),
            410 to mapOf(1 to 32, 2 to 21, 3 to 20, 4 to 25, 5 to 19),
            420 to mapOf(1 to 31, 2 to 21, 3 to 19, 4 to 24, 5 to 18),
            430 to mapOf(1 to 31, 2 to 21, 3 to 19, 4 to 23, 5 to 18),
            440 to mapOf(1 to 31, 2 to 21, 3 to 19, 4 to 23, 5 to 18),
            450 to mapOf(1 to 31, 2 to 21, 3 to 19, 4 to 22, 5 to 17),
            460 to mapOf(1 to 30, 2 to 20, 3 to 18, 4 to 22, 5 to 17),
            470 to mapOf(1 to 30, 2 to 20, 3 to 18, 4 to 21, 5 to 16),
            480 to mapOf(1 to 30, 2 to 20, 3 to 18, 4 to 20, 5 to 16),
            490 to mapOf(1 to 30, 2 to 20, 3 to 18, 4 to 20, 5 to 16),
            500 to mapOf(1 to 29, 2 to 20, 3 to 18, 4 to 19, 5 to 15),
            510 to mapOf(1 to 29, 2 to 20, 3 to 18, 4 to 19, 5 to 15),
            520 to mapOf(1 to 29, 2 to 20, 3 to 17, 4 to 18, 5 to 15),
            530 to mapOf(1 to 29, 2 to 19, 3 to 17, 4 to 18, 5 to 14),
            540 to mapOf(1 to 29, 2 to 19, 3 to 17, 4 to 17, 5 to 14)
        )
    }
    
    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text(
                text = "贵客必来份数对照表",
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold
            )
        },
        text = {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .heightIn(max = 600.dp)
                    .verticalScroll(rememberScrollState())
            ) {
                // 表头
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .background(MaterialTheme.colorScheme.primaryContainer)
                        .padding(8.dp)
                ) {
                    // 贵客率列
                    Text(
                        text = "贵客率",
                        modifier = Modifier.weight(1f),
                        fontSize = 14.sp,
                        fontWeight = FontWeight.Bold,
                        textAlign = TextAlign.Center,
                        color = MaterialTheme.colorScheme.onPrimaryContainer
                    )
                    // 5星到1星列（倒序）
                    repeat(5) { index ->
                        val star = 5 - index
                        Text(
                            text = "${star}星",
                            modifier = Modifier.weight(1f),
                            fontSize = 14.sp,
                            fontWeight = FontWeight.Bold,
                            textAlign = TextAlign.Center,
                            color = MaterialTheme.colorScheme.onPrimaryContainer
                        )
                    }
                }
                
                // 保底份数行（放在表头下方，作为第一行数据）
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .background(MaterialTheme.colorScheme.secondaryContainer)
                        .padding(vertical = 4.dp, horizontal = 8.dp)
                ) {
                    // 保底份数列
                    Text(
                        text = "保底份数",
                        modifier = Modifier.weight(1f),
                        fontSize = 10.sp,
                        textAlign = TextAlign.Center,
                        color = MaterialTheme.colorScheme.onSecondaryContainer,
                        fontWeight = FontWeight.Bold
                    )
                    
                    // 5星到1星保底份数列（倒序）
                    val guaranteedPortions = listOf(7, 10, 12, 15, 20) // 5星、4星、3星、2星、1星
                    repeat(5) { index ->
                        val star = 5 - index
                        val portions = guaranteedPortions[index]
                        
                        Text(
                            text = portions.toString(),
                            modifier = Modifier.weight(1f),
                            fontSize = 12.sp,
                            textAlign = TextAlign.Center,
                            color = MaterialTheme.colorScheme.onSecondaryContainer,
                            fontWeight = FontWeight.Bold
                        )
                    }
                }
                
                // 数据行
                guestPortionTable.entries.sortedByDescending { it.key }.forEach { (guestRate, starData) ->
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(vertical = 4.dp, horizontal = 8.dp)
                    ) {
                        // 贵客率列
                        Text(
                            text = "${guestRate}%",
                            modifier = Modifier.weight(1f),
                            fontSize = 12.sp,
                            textAlign = TextAlign.Center,
                            color = MaterialTheme.colorScheme.onSurface,
                            fontWeight = FontWeight.Bold
                        )
                        
                        // 5星到1星份数列（倒序）
                        repeat(5) { index ->
                            val star = 5 - index
                            val portions = starData[star] ?: 0
                            val textColor = if (portions > 0) Color.Red else Color.Gray
                            
                            Text(
                                text = if (portions > 0) portions.toString() else "-",
                                modifier = Modifier.weight(1f),
                                fontSize = 12.sp,
                                textAlign = TextAlign.Center,
                                color = textColor,
                                fontWeight = if (portions > 0) FontWeight.Bold else FontWeight.Normal
                            )
                        }
                    }
                }
                

            }
        },
        confirmButton = {
            TextButton(onClick = onDismiss) {
                Text("关闭")
            }
        }
    )
}

/**
 * 符文列表内容组件
 */
@Composable
private fun RuneListContent(
    runes: List<String>,
    categoryName: String
) {
    LazyColumn(
        modifier = Modifier.fillMaxWidth(),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        item {
            Text(
                text = "$categoryName (${runes.size}种)",
                fontSize = 14.sp,
                fontWeight = FontWeight.Medium,
                color = MaterialTheme.colorScheme.primary,
                modifier = Modifier.padding(bottom = 8.dp)
            )
        }
        
        // 将符文列表按每两个分组
        val runeRows = runes.chunked(2)
        
        items(runeRows) { runeRow ->
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                runeRow.forEach { rune ->
                    Card(
                        modifier = Modifier
                            .weight(1f)
                            .padding(vertical = 2.dp),
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.surfaceVariant
                        ),
                        elevation = CardDefaults.cardElevation(defaultElevation = 1.dp)
                    ) {
                        Text(
                            text = rune,
                            fontSize = 14.sp,
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(12.dp),
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            textAlign = TextAlign.Center
                        )
                    }
                }
                
                // 如果这一行只有一个符文，添加空白占位符保持布局一致
                if (runeRow.size == 1) {
                    Spacer(modifier = Modifier.weight(1f))
                }
            }
        }
    }
}

/**
 * 查询符文对应的菜谱（按时间升序排序）
 * @param rune 符文名称
 * @param gameData 游戏数据
 * @param skills 技能列表
 * @return 排序后的菜谱列表
 */
private fun queryRuneRecipes(rune: String, gameData: com.example.show_auto.data.GameData?, skills: List<com.example.show_auto.data.Skill>): List<com.example.show_auto.data.Recipe> {
    if (gameData == null) {
        System.out.println("游戏数据为空，无法查询符文菜谱")
        return emptyList()
    }
    
    // 根据符文名称查询对应的菜谱
    // 这里需要根据实际的符文-菜谱对应关系来实现
    // 暂时返回一些示例数据，按时间升序排序
    
    val runeRecipeMap = mapOf(
        "五星炒果" to listOf(
            "苹果派" to 120,
            "水果沙拉" to 90,
            "果酱面包" to 60,
            "水果蛋糕" to 180
        ),
        "香烤鱼排" to listOf(
            "烤鱼排" to 150,
            "煎鱼排" to 120,
            "蒸鱼排" to 90,
            "炸鱼排" to 180
        ),
        "千年煮鳖" to listOf(
            "清炖鳖汤" to 300,
            "红烧鳖" to 240,
            "鳖肉粥" to 180
        ),
        "鼓风机" to listOf(
            "烤鸡" to 200,
            "烤鸭" to 250,
            "烤鹅" to 300
        ),
        "蒸馏杯" to listOf(
            "蒸馏水" to 60,
            "蒸馏酒" to 120,
            "蒸馏茶" to 90
        ),
        "恐怖利刃" to listOf(
            "切丝菜" to 30,
            "切片菜" to 45,
            "切丁菜" to 60
        )
    )
    
    val recipes = runeRecipeMap[rune] ?: emptyList()
    
    if (recipes.isNotEmpty()) {
        System.out.println("符文 $rune 找到 ${recipes.size} 个菜谱")
        
        // 按时间升序排序
        val sortedRecipes = recipes.sortedBy { it.second }
        
        // 转换为Recipe对象（这里需要根据实际的Recipe数据结构调整）
        return sortedRecipes.map { (name, time) ->
            // 创建临时的Recipe对象，实际使用时需要从gameData中获取真实数据
            com.example.show_auto.data.Recipe(
                recipeId = "temp_${name.hashCode()}",
                name = name,
                rarity = 3, // 默认3星，实际应该从数据中获取
                time = time,
                origin = "符文:$rune"
            )
        }
    }
    
    System.out.println("符文 $rune 未找到对应菜谱")
    return emptyList()
}

/**
 * 根据菜谱星级和贵客率获取必来份数
 * @param recipeRarity 菜谱星级 (1-5)
 * @param guestRate 贵客率百分比
 * @return 必来份数，如果超出范围返回null
 */
fun getRequiredPortionsForGuest(recipeRarity: Int, guestRate: Int): Int? {
    // 贵客率-份数对照表数据（完整的1-5星菜谱数据）
    val guestPortionTable = mapOf(
        // 保底份数行
        7 to mapOf(1 to 0, 2 to 0, 3 to 0, 4 to 0, 5 to 540),
        10 to mapOf(1 to 0, 2 to 0, 3 to 0, 4 to 0, 5 to 500),
        12 to mapOf(1 to 0, 2 to 0, 3 to 0, 4 to 0, 5 to 460),
        15 to mapOf(1 to 0, 2 to 0, 3 to 0, 4 to 0, 5 to 420),
        17 to mapOf(1 to 0, 2 to 0, 3 to 0, 4 to 0, 5 to 380),
        19 to mapOf(1 to 0, 2 to 0, 3 to 0, 4 to 0, 5 to 340),
        20 to mapOf(1 to 0, 2 to 0, 3 to 0, 4 to 0, 5 to 320),
        22 to mapOf(1 to 0, 2 to 0, 3 to 0, 4 to 0, 5 to 300),
        25 to mapOf(1 to 0, 2 to 0, 3 to 0, 4 to 0, 5 to 280),
        27 to mapOf(1 to 0, 2 to 0, 3 to 0, 4 to 0, 5 to 260),
        30 to mapOf(1 to 0, 2 to 0, 3 to 0, 4 to 0, 5 to 240),
        33 to mapOf(1 to 0, 2 to 0, 3 to 0, 4 to 0, 5 to 220),
        36 to mapOf(1 to 0, 2 to 0, 3 to 0, 4 to 0, 5 to 200),
        39 to mapOf(1 to 0, 2 to 0, 3 to 0, 4 to 0, 5 to 180),
        42 to mapOf(1 to 0, 2 to 0, 3 to 0, 4 to 0, 5 to 160),
        46 to mapOf(1 to 0, 2 to 0, 3 to 0, 4 to 0, 5 to 140),
        50 to mapOf(1 to 0, 2 to 0, 3 to 0, 4 to 0, 5 to 120),
        55 to mapOf(1 to 0, 2 to 0, 3 to 0, 4 to 0, 5 to 100),
        59 to mapOf(1 to 0, 2 to 0, 3 to 0, 4 to 0, 5 to 80),
        62 to mapOf(1 to 0, 2 to 0, 3 to 0, 4 to 0, 5 to 80)
    )
    
    // 查找最接近的贵客率
    val closestPortion = guestPortionTable.entries.minByOrNull { (_, starData) ->
        val targetRate = starData[recipeRarity] ?: 0
        if (targetRate == 0) Int.MAX_VALUE else kotlin.math.abs(targetRate - guestRate)
    }
    
    return closestPortion?.key
}

/**
 * 获取厨师技能描述（用于显示）
 */
private fun getChefSkillDescription(chef: com.example.show_auto.data.Chef, skills: List<com.example.show_auto.data.Skill>): String {
    if (!chef.hasUltimateSkill()) return "无修炼技能"
    val descs = chef.getAllUltimateSkills().mapNotNull { sid ->
        skills.find { it.skillId == sid }?.desc
    }
    return if (descs.isEmpty()) "无修炼技能" else descs.joinToString("、")
}

/**
 * 获取厨师技能描述（用于计算，未修炼厨师不包含修炼技能）
 */
private fun getChefSkillDescriptionForCalculation(chef: com.example.show_auto.data.Chef, skills: List<com.example.show_auto.data.Skill>): String {
    // 如果厨师未修炼（ult = false），则不返回修炼技能
    if (!chef.ult) return "无修炼技能"
    
    if (!chef.hasUltimateSkill()) return "无修炼技能"
    val descs = chef.getAllUltimateSkills().mapNotNull { sid ->
        skills.find { it.skillId == sid }?.desc
    }
    return if (descs.isEmpty()) "无修炼技能" else descs.joinToString("、")
}

/**
 * 获取厨师技能描述（用于计算，支持默认全修炼开关）
 */
private fun getChefSkillDescriptionForCalculationWithOverride(chef: com.example.show_auto.data.Chef, skills: List<com.example.show_auto.data.Skill>, defaultAllUltimate: Boolean): String {
    // 如果开启默认全修炼，则所有厨师都视为已修炼
    if (defaultAllUltimate) {
        // 直接获取修炼技能，不检查chef.ult状态
        val ultimateSkillIds = chef.getAllUltimateSkills()
        val descs = ultimateSkillIds.mapNotNull { sid ->
            skills.find { it.skillId == sid }?.desc
        }
        
        // 调试信息（已注释，避免重复打印）
        // println("DEBUG: defaultAllUltimate=true, chef=${chef.name}, ultimateSkillIds=$ultimateSkillIds, descs=$descs")
        
        return if (descs.isEmpty()) "无修炼技能" else descs.joinToString("、")
    } else {
        // 使用原来的逻辑
        return getChefSkillDescriptionForCalculation(chef, skills)
    }
}

/**
 * 贵客厨师筛选逻辑
 */
private fun isAuraChef(chef: com.example.show_auto.data.Chef, skills: List<com.example.show_auto.data.Skill>): Boolean {
    // 获取厨师的修炼技能描述（使用默认全修炼设置）
    val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(chef, skills, true) // 默认开启全修炼
    
    // 获取厨师的基础技能描述
    val baseSkillDesc = if (chef.skill > 0) {
        skills.find { it.skillId == chef.skill }?.desc ?: ""
    } else {
        ""
    }
    
    // 合并所有技能描述
    val allSkillDescs = listOf(ultimateSkillDesc, baseSkillDesc).filter { it.isNotEmpty() }
    
    // 检查是否匹配贵客相关技能
    return allSkillDescs.any { desc ->
        isGuestRelatedSkill(desc)
    }
}

/**
 * 检查技能描述是否为贵客相关技能
 */
private fun isGuestRelatedSkill(desc: String): Boolean {
    // 稀有客人出现概率+*%
    if (desc.contains("稀有客人出现概率+") && desc.contains("%")) {
        return true
    }
    
    // 稀有客人赠礼数量*%概率提升*%
    if (desc.contains("稀有客人赠礼数量") && desc.contains("%概率提升") && desc.contains("%")) {
        return true
    }
    
    // 场上男性厨师稀有客人出现概率+*%
    if (desc.contains("场上男性厨师稀有客人出现概率+") && desc.contains("%")) {
        return true
    }
    
    // 场上女性厨师贵客率+*%
    if (desc.contains("场上女性厨师贵客率+") && desc.contains("%")) {
        return true
    }
    
    // 每制作一种神级料理稀有客人出现概率+*%
    if (desc.contains("每制作一种神级料理稀有客人出现概率+") && desc.contains("%")) {
        return true
    }
    
    // 场上厨师制作特级及以上料理时此料理贵客符文概率+*%
    if (desc.contains("场上厨师制作特级及以上料理时此料理贵客符文概率+") && desc.contains("%")) {
        return true
    }
    
    // 开业时间-*% 特殊处理：数值大于10才能查询到
    if (desc.contains("开业时间-") && desc.contains("%")) {
        // 提取数值
        val regex = Regex("开业时间-(\\d+)%")
        val matchResult = regex.find(desc)
        if (matchResult != null) {
            val value = matchResult.groupValues[1].toIntOrNull() ?: 0
            return value > 10
        }
    }
    
    // 厨具技能效果翻倍
    if (desc.contains("厨具技能效果翻倍")) {
        return true
    }
    
    return false
}

/**
 * 计算厨师的总贵客率加成
 * @param chef 厨师数据
 * @param skills 技能数据列表
 * @param gameData 游戏数据（用于获取厨具和心法盘信息）
 * @param personalData 个人数据（用于获取厨师佩戴的厨具和心法盘）
 * @return 总贵客率加成百分比，只计算基础的"稀有客人出现概率+X%"技能
 */
private fun calculateTotalGuestRateBonus(
    chef: com.example.show_auto.data.Chef, 
    skills: List<com.example.show_auto.data.Skill>,
    gameData: com.example.show_auto.data.GameData? = null,
    personalData: com.example.show_auto.data.PersonalData? = null
): Double {
    var totalBonus = 0.0
    
    // 1. 计算厨师技能加成
    // 获取基础技能描述
    val baseSkillDesc = if (chef.skill > 0) {
        skills.find { it.skillId == chef.skill }?.desc ?: ""
    } else {
        ""
    }
    
    // 获取修炼技能描述
    val ultimateSkillDesc = getChefSkillDescriptionForCalculation(chef, skills)
    
    // 合并厨师技能描述
    val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
    
    // 计算厨师技能中的贵客率加成
    totalBonus += calculateChefSkillGuestRateBonus(combinedSkillDesc, chef)
    
    // 如果没有游戏数据或个人数据，返回厨师技能加成
    if (gameData == null || personalData == null) {
        return totalBonus
    }
    
    // 定义贵客率正则表达式（用于厨具和心法盘）
    val guestRatePattern = "稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
    
    // 2. 计算厨具加成
    val equipId = personalData.chefs[chef.chefId]?.equip
    if (equipId != null) {
        val equip = gameData.equips.find { it.equipId == equipId.toString() }
        if (equip != null) {
            // 检查厨师是否有厨具技能效果翻倍技能
            val hasEquipSkillMultiplier = hasEquipSkillMultiplier(chef, skills)
            val multiplier = if (hasEquipSkillMultiplier) 2.0 else 1.0
            
            // 遍历厨具的所有技能
            for (skillId in equip.skill) {
                val skill = skills.find { it.skillId == skillId }
                if (skill != null) {
                    val equipMatches = guestRatePattern.findAll(skill.desc)
                    for (equipMatch in equipMatches) {
                        val value = equipMatch.groupValues[1].toDoubleOrNull() ?: 0.0
                        totalBonus += value * multiplier
                    }
                }
            }
        }
    }
    
    // 3. 计算心法盘加成
    val pChef = personalData.chefs[chef.chefId]
    val diskLevel = (pChef?.dlv ?: 1).coerceAtLeast(1)
    val amberIds = pChef?.ambers ?: emptyList()
    
    if (amberIds.isNotEmpty()) {
        amberIds.forEach { aid ->
            if (aid == 0) return@forEach
            val amber = gameData.ambers.find { it.amberId == aid.toString() }
            if (amber != null && amber.type == 3) { // 蓝色心法盘（贵客率相关）
                val levelBonusEach = if (diskLevel > 1) amber.amplification * (diskLevel - 1) else 0
                
                // 遍历心法盘的所有技能
                amber.skill.forEach { sid ->
                    val skillObj = skills.find { it.skillId == sid }
                    if (skillObj != null) {
                        val amberMatches = guestRatePattern.findAll(skillObj.desc)
                        for (amberMatch in amberMatches) {
                            val baseValue = amberMatch.groupValues[1].toDoubleOrNull() ?: 0.0
                            val totalValue = baseValue + levelBonusEach
                            totalBonus += totalValue
                        }
                    }
                }
            }
        }
    }
    
    return totalBonus
}

/**
 * 检查厨师是否有厨具技能效果翻倍技能
 * @param chef 厨师数据
 * @param skills 技能数据列表
 * @return true表示有厨具技能效果翻倍
 */
private fun hasEquipSkillMultiplier(chef: com.example.show_auto.data.Chef, skills: List<com.example.show_auto.data.Skill>): Boolean {
    // 获取基础技能描述
    val baseSkillDesc = if (chef.skill > 0) {
        skills.find { it.skillId == chef.skill }?.desc ?: ""
    } else {
        ""
    }
    
    // 获取修炼技能描述
    val ultimateSkillDesc = getChefSkillDescription(chef, skills)
    
    // 合并厨师技能描述
    val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
    
    // 检查是否包含厨具技能效果翻倍
    return combinedSkillDesc.contains("厨具技能效果翻倍")
}

/**
 * 计算厨师技能中的贵客率加成
 * @param skillDesc 厨师技能描述（基础技能+修炼技能）
 * @param chef 厨师数据（用于判断性别）
 * @return 贵客率加成百分比
 */
private fun calculateChefSkillGuestRateBonus(skillDesc: String, chef: com.example.show_auto.data.Chef): Double {
    var totalBonus = 0.0
    
    // 1. 先计算"每制作一种神级料理稀有客人出现概率+*%"技能
    // 例：每制作一种神级料理稀有客人出现概率+10% -> 10 * 3 = 30%
    val divineRecipePattern = "每制作一种神级料理稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
    val divineRecipeMatches = divineRecipePattern.findAll(skillDesc)
    for (match in divineRecipeMatches) {
        val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
        totalBonus += value * 3 // 每个厨师最多制作3道菜
    }
    
    // 2. 再计算基础的"稀有客人出现概率+*%"技能
    // 注意：这里要排除已经计算过的其他技能，使用完全匹配
    // 使用负向前瞻断言来确保不匹配到其他包含"稀有客人出现概率+"的技能
    val baseGuestRatePattern = "(?<!每制作一种神级料理)(?<!场上男性厨师)(?<!场上女性厨师)稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
    val baseGuestRateMatches = baseGuestRatePattern.findAll(skillDesc)
    for (match in baseGuestRateMatches) {
        val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
        totalBonus += value
    }
    
    // 3. 计算"场上女性厨师贵客率+*%"技能
    // 例：场上女性厨师贵客率+20% -> 只有女性厨师才能获得此技能加成
    val femaleChefPattern = "场上女性厨师贵客率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
    val femaleChefMatches = femaleChefPattern.findAll(skillDesc)
    for (match in femaleChefMatches) {
        val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
        // 只有女性厨师（tags[0] == 2）才能获得此技能加成
        if (chef.tags.isNotEmpty() && chef.tags[0] == 2) {
            totalBonus += value
        }
    }
    
    // 4. 计算"场上男性厨师稀有客人出现概率+*%"技能
    // 例：场上男性厨师稀有客人出现概率+15% -> 只有男性厨师才能获得此技能加成
    val maleChefPattern = "场上男性厨师稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
    val maleChefMatches = maleChefPattern.findAll(skillDesc)
    for (match in maleChefMatches) {
        val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
        // 只有男性厨师（tags[0] == 1）才能获得此技能加成
        if (chef.tags.isNotEmpty() && chef.tags[0] == 1) {
            totalBonus += value
        }
    }
    
    return totalBonus
}

/**
 * 计算受心法盘影响的技法值
 * @param chef 厨师数据
 * @param skills 技能数据列表
 * @param gameData 游戏数据
 * @param selectedLevel 计算器中选择的等级
 * @param selectedAmbers 计算器中选择的心法盘列表
 * @param enhancedChef 已经计算了个人加成和厨师间影响的厨师数据
 * @return 技法值映射，包含基础值和受心法盘影响的值
 */
private fun calculateTechniqueValuesWithAmbers(
    chef: com.example.show_auto.data.Chef,
    skills: List<com.example.show_auto.data.Skill>,
    gameData: com.example.show_auto.data.GameData?,
    selectedLevel: Int?,
    selectedAmbers: List<com.example.show_auto.data.Amber?>?,
    enhancedChef: com.example.show_auto.data.Chef
): Map<String, Pair<Int, Int>> {
    val techniques = mapOf(
        "stirfry" to enhancedChef.stirfry,
        "boil" to enhancedChef.boil,
        "knife" to enhancedChef.knife,
        "fry" to enhancedChef.fry,
        "bake" to enhancedChef.bake,
        "steam" to enhancedChef.steam
    )
    
    val result = mutableMapOf<String, Pair<Int, Int>>()
    
    // 初始化结果，基础值 = 已经包含个人加成和厨师间影响的值
    techniques.forEach { (key, value) ->
        result[key] = Pair(value, value)
    }
    
    // 如果没有心法盘数据，返回基础值
    if (selectedAmbers == null || gameData == null) {
        return result
    }
    
    // 心法盘等级：如果手动选择了等级则使用选择的等级，否则根据厨师星级判断
    val diskLevel = selectedLevel ?: when (chef.rarity) {
        5 -> 5
        4 -> 4
        else -> 3
    }
    
    // 计算红色心法盘对技法的影响（百分比加成，向上取整）
    selectedAmbers.forEach { amber ->
        if (amber != null && amber.type == 1) { // 红色心法盘
            val levelBonusEach = if (diskLevel > 1) amber.amplification * (diskLevel - 1) else 0
            
            // 遍历心法盘的所有技能
            amber.skill.forEach { skillId ->
                val skill = skills.find { it.skillId == skillId }
                if (skill != null) {
                    // 匹配技法加成技能
                    val techniquePattern = "(\\w+)技法\\+(\\d+)%".toRegex()
                    val matches = techniquePattern.findAll(skill.desc)
                    
                    for (match in matches) {
                        val techniqueType = match.groupValues[1]
                        val bonusPercentage = match.groupValues[2].toIntOrNull() ?: 0
                        val totalBonusPercentage = bonusPercentage + levelBonusEach
                        
                        // 将中文技法名转换为英文key
                        val techniqueKey = when (techniqueType) {
                            "炒" -> "stirfry"
                            "煮" -> "boil"
                            "切" -> "knife"
                            "炸" -> "fry"
                            "烤" -> "bake"
                            "蒸" -> "steam"
                            else -> null
                        }
                        
                        if (techniqueKey != null) {
                            val current = result[techniqueKey] ?: Pair(0, 0)
                            // 计算百分比加成：基础值 * (1 + 百分比/100)，然后向上取整
                            val percentageMultiplier = 1.0 + (totalBonusPercentage / 100.0)
                            val bonusValue = kotlin.math.ceil(current.first * percentageMultiplier).toInt() - current.first
                            result[techniqueKey] = Pair(current.first, current.first + bonusValue)
                        }
                    }
                }
            }
        }
    }
    
    return result
}

/**
 * 计算厨师的总贵客率加成，支持默认满级心法盘
 * @param chef 厨师数据
 * @param skills 技能数据列表
 * @param gameData 游戏数据
 * @param personalData 个人数据
 * @param useMaxLevelAmber 是否使用满级心法盘
 * @return 总贵客率加成百分比
 */
private fun calculateTotalGuestRateBonusWithMaxAmber(
    chef: com.example.show_auto.data.Chef,
    skills: List<com.example.show_auto.data.Skill>,
    gameData: com.example.show_auto.data.GameData? = null,
    personalData: com.example.show_auto.data.PersonalData? = null,
    useMaxLevelAmber: Boolean = false,
    defaultAllUltimate: Boolean = false
): Double {
    var totalBonus = 0.0
    
    // 1. 计算厨师技能加成
    val baseSkillDesc = if (chef.skill > 0) {
        skills.find { it.skillId == chef.skill }?.desc ?: ""
    } else {
        ""
    }
    
    val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(chef, skills, defaultAllUltimate)
    val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
    
    totalBonus += calculateChefSkillGuestRateBonus(combinedSkillDesc, chef)
    
    // 2. 计算厨具加成
    val personalChef = personalData?.chefs?.get(chef.chefId)
    val equip = if (personalChef?.equip != null && gameData != null) {
        gameData.equips.find { it.equipId == personalChef.equip.toString() }
    } else null
    
    if (equip != null) {
        // 检查厨师是否有厨具技能效果翻倍技能
        val hasEquipSkillMultiplier = hasEquipSkillMultiplier(chef, skills)
        val multiplier = if (hasEquipSkillMultiplier) 2.0 else 1.0
        
        val guestRatePattern = "稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
        for (skillId in equip.skill) {
            val skill = skills.find { it.skillId == skillId }
            if (skill != null) {
                val equipMatches = guestRatePattern.findAll(skill.desc)
                for (equipMatch in equipMatches) {
                    val value = equipMatch.groupValues[1].toDoubleOrNull() ?: 0.0
                    totalBonus += value * multiplier
                }
            }
        }
    }
    
    // 3. 计算心法盘加成
    if (gameData != null) {
        val diskLevel = if (useMaxLevelAmber) {
            when (chef.rarity) {
                5 -> 5
                4 -> 4
                else -> 3
            }
        } else {
            personalChef?.dlv ?: 1
        }
        
        // 构建心法盘配置
        val ambers = if (useMaxLevelAmber) {
            // 使用满朋陨配置
            val defaultAmbers = mutableListOf<com.example.show_auto.data.Amber?>(null, null, null)
            applyMaxLevelAmberToBluePositions(chef, defaultAmbers, gameData, true)
            defaultAmbers
        } else {
            // 使用个人数据中的心法盘
            val chefAmbers = mutableListOf<com.example.show_auto.data.Amber?>()
            personalChef?.ambers?.forEach { amberId ->
                val amber = gameData.ambers.find { it.amberId == amberId.toString() }
                chefAmbers.add(amber)
            }
            while (chefAmbers.size < 3) {
                chefAmbers.add(null)
            }
            chefAmbers
        }
        
        val guestRatePattern = "稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
        ambers.forEach { amber ->
            if (amber != null && amber.type == 3) { // 蓝色心法盘（贵客率相关）
                val levelBonusEach = if (diskLevel > 1) amber.amplification * (diskLevel - 1) else 0
                
                amber.skill.forEach { skillId ->
                    val skill = skills.find { it.skillId == skillId }
                    if (skill != null) {
                        val amberMatches = guestRatePattern.findAll(skill.desc)
                        for (amberMatch in amberMatches) {
                            val baseValue = amberMatch.groupValues[1].toDoubleOrNull() ?: 0.0
                            val totalValue = baseValue + levelBonusEach
                            totalBonus += totalValue
                        }
                    }
                }
            }
        }
    }
    
    return totalBonus
}

/**
 * 计算厨师的总贵客率加成，使用指定的厨具
 * @param chef 厨师数据
 * @param equip 指定的厨具（可以为null）
 * @param skills 技能数据列表
 * @param gameData 游戏数据（用于获取心法盘信息）
 * @param personalData 个人数据（用于获取心法盘信息）
 * @return 总贵客率加成百分比，只计算基础的"稀有客人出现概率+X%"技能
 */
private fun calculateTotalGuestRateBonusWithEquip(
    chef: com.example.show_auto.data.Chef, 
    equip: com.example.show_auto.data.Equip?,
    skills: List<com.example.show_auto.data.Skill>,
    gameData: com.example.show_auto.data.GameData? = null,
    personalData: com.example.show_auto.data.PersonalData? = null,
    defaultAllUltimate: Boolean = false
): Double {
    var totalBonus = 0.0
    
    // 1. 计算厨师技能加成
    // 获取基础技能描述
    val baseSkillDesc = if (chef.skill > 0) {
        skills.find { it.skillId == chef.skill }?.desc ?: ""
    } else {
        ""
    }
    
    // 获取修炼技能描述
    val ultimateSkillDesc = getChefSkillDescription(chef, skills)
    
    // 合并厨师技能描述
    val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
    
    // 计算厨师技能中的贵客率加成
    totalBonus += calculateChefSkillGuestRateBonus(combinedSkillDesc, chef)
    
    // 如果没有游戏数据或个人数据，返回厨师技能加成
    if (gameData == null || personalData == null) {
        return totalBonus
    }
    
    // 定义贵客率正则表达式（用于厨具和心法盘）
    val guestRatePattern = "稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
    
    // 2. 计算厨具加成（使用传入的equip参数）
    if (equip != null) {
        // 检查厨师是否有厨具技能效果翻倍技能
        val hasEquipSkillMultiplier = hasEquipSkillMultiplier(chef, skills)
        val multiplier = if (hasEquipSkillMultiplier) 2.0 else 1.0
        
        // 遍历厨具的所有技能
        for (skillId in equip.skill) {
            val skill = skills.find { it.skillId == skillId }
            if (skill != null) {
                val equipMatches = guestRatePattern.findAll(skill.desc)
                for (equipMatch in equipMatches) {
                    val value = equipMatch.groupValues[1].toDoubleOrNull() ?: 0.0
                    totalBonus += value * multiplier
                }
            }
        }
    }
    
    // 3. 计算心法盘加成
    val pChef = personalData.chefs[chef.chefId]
    val diskLevel = (pChef?.dlv ?: 1).coerceAtLeast(1)
    val amberIds = pChef?.ambers ?: emptyList()
    
    if (amberIds.isNotEmpty()) {
        amberIds.forEach { aid ->
            if (aid == 0) return@forEach
            val amber = gameData.ambers.find { it.amberId == aid.toString() }
            if (amber != null && amber.type == 3) { // 蓝色心法盘（贵客率相关）
                val levelBonusEach = if (diskLevel > 1) amber.amplification * (diskLevel - 1) else 0
                
                // 遍历心法盘的所有技能
                amber.skill.forEach { sid ->
                    val skillObj = skills.find { it.skillId == sid }
                    if (skillObj != null) {
                        val amberMatches = guestRatePattern.findAll(skillObj.desc)
                        for (amberMatch in amberMatches) {
                            val baseValue = amberMatch.groupValues[1].toDoubleOrNull() ?: 0.0
                            val totalValue = baseValue + levelBonusEach
                            totalBonus += totalValue
                        }
                    }
                }
            }
        }
    }
    
    return totalBonus
}

/**
 * 技法行组件 - 从RecipeCalculatorPage复制
 */
@Composable
private fun SkillRow(
    chef: com.example.show_auto.data.Chef,
    ultimateSkills: UltimateSkillsState,
    equip: com.example.show_auto.data.Equip?,
    skills: List<com.example.show_auto.data.Skill>,
    chefInteractionBonus: Map<String, Int>?,
    skillTypes: List<String>,
    skillNames: List<String>
) {
    val enhancedChef = ChefSkillCalculator.applyAllSkills(chef, ultimateSkills, equip, skills, chefInteractionBonus)

    Row {
        skillTypes.forEachIndexed { index, skillType ->
            val skillValue = when (skillType) {
                "stirfry" -> enhancedChef.stirfry
                "boil" -> enhancedChef.boil
                "knife" -> enhancedChef.knife
                "fry" -> enhancedChef.fry
                "bake" -> enhancedChef.bake
                "steam" -> enhancedChef.steam
                else -> 0
            }

            val skillColor = when {
                ChefSkillCalculator.hasSpecificChefInteractionBonus(chefInteractionBonus, skillType) &&
                ChefSkillCalculator.hasSpecificEquipSkillBonus(chef, equip, skills, skillType) ->
                    Color(0xFF9C27B0) // 紫色：同时有厨师间技法影响和厨具技能加成
                ChefSkillCalculator.hasSpecificChefInteractionBonus(chefInteractionBonus, skillType) ->
                    MaterialTheme.colorScheme.primary // 蓝色：厨师间技法影响
                ChefSkillCalculator.hasSpecificEquipSkillBonus(chef, equip, skills, skillType) ->
                    Color(0xFF4CAF50) // 绿色：厨具技能加成
                else -> MaterialTheme.colorScheme.onSurfaceVariant // 正常颜色：包括个人技法加成
            }

            Text(
                text = "${skillNames[index]}${skillValue.toString().padStart(3)}",
                fontSize = 8.sp,
                color = skillColor,
                fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace
            )

            if (index < skillTypes.size - 1) {
                Text(
                    text = " ",
                    fontSize = 8.sp,
                    fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace
                )
            }
        }
    }
}

/**
 * 贵客率详情弹窗 - 完全复刻素材详情弹窗的设计
 */
@Composable
private fun GuestRateDetailDialog(
    chef: com.example.show_auto.data.Chef,
    skills: List<com.example.show_auto.data.Skill>,
    gameData: com.example.show_auto.data.GameData?,
    personalData: com.example.show_auto.data.PersonalData?,
    defaultMaxLevelAmber: Boolean,
    defaultAllUltimate: Boolean,
    onDismiss: () -> Unit,
    otherSelectedChefs: List<com.example.show_auto.data.Chef> = emptyList()
) {
    val context = LocalContext.current
    val settingsStorage = remember { com.example.show_auto.data.SettingsStorage(context) }
    
    // 实时读取心法盘默认满级设置状态，确保开关变化时立即生效
    var currentMaxLevelAmber by remember { mutableStateOf(defaultMaxLevelAmber) }
    
    Dialog(
        onDismissRequest = onDismiss,
        properties = WindowDialogProperties(
            dismissOnBackPress = true,
            dismissOnClickOutside = true
        )
    ) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
            elevation = CardDefaults.cardElevation(defaultElevation = 0.dp),
            shape = RoundedCornerShape(16.dp)
        ) {
            Column(
                modifier = Modifier.padding(16.dp), // 与素材详情一致的16dp padding
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                // 标题行 - 完全复刻素材详情的标题样式
                Row(
                    modifier = Modifier.fillMaxWidth(), // 移除额外padding，因为Column已有16dp
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text(
                        text = "${chef.name} 贵客率详情",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.primary
                    )
                    
                    // 显示蓝色心法盘数量（类似素材详情中的绿色心法盘显示）
                    if (gameData != null && personalData != null) {
                        val blueAmberCount = getBlueAmberCount(chef, gameData, personalData)
                        val displayText = if (blueAmberCount > 0) {
                            "蓝色心法盘X$blueAmberCount"
                        } else {
                            "无蓝色心法盘"
                        }
                        Text(
                            text = displayText,
                            fontSize = 12.sp,
                            fontWeight = FontWeight.Normal,
                            color = Color(0xFF2196F3) // 蓝色
                        )
                    }
                }
                
                HorizontalDivider()
                
                // 当前加成装备信息 - 复刻素材详情的装备信息显示
                val currentEquipInfo = getCurrentGuestRateEquipmentInfo(chef, gameData, personalData, currentMaxLevelAmber)
                
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Text(
                        text = "当前加成",
                        fontSize = 12.sp,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.primary
                    )
                    
                    if (currentEquipInfo.isNotEmpty()) {
                        Text(
                            text = " ",
                            fontSize = 12.sp,
                            color = MaterialTheme.colorScheme.primary
                        )
                        
                        Text(
                            text = currentEquipInfo,
                            fontSize = 9.sp,
                            fontWeight = FontWeight.Normal,
                            color = MaterialTheme.colorScheme.primary,
                            maxLines = 1,
                            overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
                            modifier = Modifier.weight(1f)
                        )
                    }
                }
                
                // 贵客率详情内容 - 使用与暴击详情相同的样式
                GuestRateDetailsContent(
                    chef = chef,
                    skills = skills,
                    gameData = gameData,
                    personalData = personalData,
                    otherSelectedChefs = otherSelectedChefs,
                    defaultMaxLevelAmber = currentMaxLevelAmber,
                    defaultAllUltimate = defaultAllUltimate
                )
            }
        }
    }
}

/**
 * 贵客率详情数据类
 */
private data class GuestRateDetail(
    val source: String,      // 来源（技能、厨具、心法盘等）
    val description: String, // 描述
    val value: Double        // 数值
)

/**
 * 计算厨师技能中的贵客率加成（用于详情展示）
 * @param skillDesc 厨师技能描述（基础技能或修炼技能）
 * @param chef 厨师数据（用于判断性别）
 * @return 贵客率加成百分比
 */
private fun calculateChefSkillGuestRateBonusForDetails(skillDesc: String, chef: com.example.show_auto.data.Chef): Double {
    var totalBonus = 0.0
    
    // 1. 先计算"每制作一种神级料理稀有客人出现概率+*%"技能
    // 例：每制作一种神级料理稀有客人出现概率+10% -> 10 * 3 = 30%
    val divineRecipePattern = "每制作一种神级料理稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
    val divineRecipeMatches = divineRecipePattern.findAll(skillDesc)
    for (match in divineRecipeMatches) {
        val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
        totalBonus += value * 3 // 每个厨师最多制作3道菜
    }
    
    // 2. 再计算基础的"稀有客人出现概率+*%"技能
    // 注意：这里要排除已经计算过的其他技能，使用完全匹配
    // 使用负向前瞻断言来确保不匹配到其他包含"稀有客人出现概率+"的技能
    val baseGuestRatePattern = "(?<!每制作一种神级料理)(?<!场上男性厨师)(?<!场上女性厨师)稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
    val baseGuestRateMatches = baseGuestRatePattern.findAll(skillDesc)
    for (match in baseGuestRateMatches) {
        val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
        totalBonus += value
    }
    
    // 3. 计算"场上女性厨师贵客率+*%"技能
    // 例：场上女性厨师贵客率+20% -> 只有女性厨师才能获得此技能加成，但这里不考虑场上其他厨师，所以返回0
    val femaleChefPattern = "场上女性厨师贵客率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
    val femaleChefMatches = femaleChefPattern.findAll(skillDesc)
    for (match in femaleChefMatches) {
        // 场上性别技能不对自己生效，在详情页面中显示为0
        // 这部分加成会在总计算中通过场上其他厨师来提供
        totalBonus += 0.0
    }
    
    // 4. 计算"场上男性厨师稀有客人出现概率+*%"技能
    // 例：场上男性厨师稀有客人出现概率+15% -> 只有男性厨师才能获得此技能加成，但这里不考虑场上其他厨师，所以返回0
    val maleChefPattern = "场上男性厨师稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
    val maleChefMatches = maleChefPattern.findAll(skillDesc)
    for (match in maleChefMatches) {
        // 场上性别技能不对自己生效，在详情页面中显示为0
        // 这部分加成会在总计算中通过场上其他厨师来提供
        totalBonus += 0.0
    }
    
    return totalBonus
}

/**
 * 计算贵客率详细加成分解
 */
private fun calculateGuestRateDetails(
    chef: com.example.show_auto.data.Chef,
    skills: List<com.example.show_auto.data.Skill>,
    gameData: com.example.show_auto.data.GameData?,
    personalData: com.example.show_auto.data.PersonalData?,
    otherSelectedChefs: List<com.example.show_auto.data.Chef> = emptyList(),
    useMaxLevelAmber: Boolean = false,
    defaultAllUltimate: Boolean = false
): List<GuestRateDetail> {
    val details = mutableListOf<GuestRateDetail>()
    
    // 1. 基础技能
    if (chef.skill > 0) {
        val baseSkill = skills.find { it.skillId == chef.skill }
        if (baseSkill != null) {
            val skillValue = calculateChefSkillGuestRateBonusForDetails(baseSkill.desc, chef)
            if (skillValue > 0) {
                details.add(GuestRateDetail(
                    source = "基础技能",
                    description = baseSkill.desc,
                    value = skillValue
                ))
            }
        }
    }
    
    // 2. 修炼技能
    val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(chef, skills, defaultAllUltimate)
    if (ultimateSkillDesc.isNotEmpty() && ultimateSkillDesc != "无修炼技能") {
        val skillValue = calculateChefSkillGuestRateBonusForDetails(ultimateSkillDesc, chef)
        if (skillValue > 0) {
            details.add(GuestRateDetail(
                source = "修炼技能",
                description = ultimateSkillDesc,
                value = skillValue
            ))
        }
    }
    
    // 3. 厨具加成
    if (personalData != null && gameData != null) {
        val guestRatePattern = "稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
        val pChef = personalData.chefs[chef.chefId]
        val equipId = pChef?.equip?.toString() ?: "0"
        val equip = gameData.equips.find { it.equipId == equipId }
        
        if (equip != null) {
            equip.skill.forEach { sid ->
                val skillObj = skills.find { it.skillId == sid }
                if (skillObj != null) {
                    val matches = guestRatePattern.findAll(skillObj.desc)
                    for (match in matches) {
                        val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
                        if (value > 0) {
                            details.add(GuestRateDetail(
                                source = "厨具：${equip.name}",
                                description = skillObj.desc,
                                value = value
                            ))
                        }
                    }
                }
            }
        }
    }
    
    // 4. 心法盘加成
    if (personalData != null && gameData != null) {
        val guestRatePattern = "稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
        val pChef = personalData.chefs[chef.chefId]
        
        val (diskLevel, ambers) = if (useMaxLevelAmber) {
            // 使用满朋陨配置
            val level = when (chef.rarity) {
                5 -> 5
                4 -> 4
                else -> 3
            }
            val defaultAmbers = mutableListOf<com.example.show_auto.data.Amber?>(null, null, null)
            applyMaxLevelAmberToBluePositions(chef, defaultAmbers, gameData, true)
            level to defaultAmbers.filterNotNull()
        } else {
            // 启用厨具遗玉
            val level = (pChef?.dlv ?: 1).coerceAtLeast(1)
            val amberIds = pChef?.ambers ?: emptyList()
            val amberList = amberIds.mapNotNull { aid ->
                if (aid == 0) return@mapNotNull null
                gameData.ambers.find { it.amberId == aid.toString() }
            }
            level to amberList
        }
        
        if (ambers.isNotEmpty()) {
            // 统计每个心法盘的数量和总加成
            val amberCountMap = mutableMapOf<String, Double>()
            
            ambers.forEach { amber ->
                if (amber.type == 3) { // 蓝色心法盘
                    val levelBonusEach = if (diskLevel > 1) amber.amplification * (diskLevel - 1) else 0
                    
                    amber.skill.forEach { sid ->
                        val skillObj = skills.find { it.skillId == sid }
                        if (skillObj != null) {
                            val matches = guestRatePattern.findAll(skillObj.desc)
                            for (match in matches) {
                                val baseValue = match.groupValues[1].toDoubleOrNull() ?: 0.0
                                val totalValue = baseValue + levelBonusEach
                                if (totalValue > 0) {
                                    // 累加相同心法盘的加成值
                                    amberCountMap[amber.name] = amberCountMap.getOrDefault(amber.name, 0.0) + totalValue
                                }
                            }
                        }
                    }
                }
            }
            
            // 添加心法盘详情，显示为"心法盘名字X数量"格式
            amberCountMap.forEach { (amberName, totalValue) ->
                val count = ambers.count { amber ->
                    amber.name == amberName && amber.type == 3
                }
                val levelText = if (diskLevel > 1) " (${diskLevel}级)" else ""
                val displayName = if (count > 1) "${amberName}×${count}" else amberName
                val sourcePrefix = if (useMaxLevelAmber) "心法盘(满级)：" else "心法盘："
                details.add(GuestRateDetail(
                    source = "${sourcePrefix}${displayName}${levelText}",
                    description = "稀有客人出现概率+${totalValue.toInt()}%",
                    value = totalValue
                ))
            }
        }
    }
    
    // 5. 来自其他厨师的性别技能加成
    if (otherSelectedChefs.isNotEmpty()) {
        val currentChefGender = if (chef.tags.isNotEmpty()) chef.tags[0] else 0
        
        otherSelectedChefs.forEach { otherChef ->
            if (otherChef.name.isNotEmpty()) {
                // 获取其他厨师的基础技能和修炼技能描述
                val baseSkillDesc = if (otherChef.skill > 0) {
                    skills.find { it.skillId == otherChef.skill }?.desc ?: ""
                } else {
                    ""
                }
                
                val ultimateSkillDesc = getChefSkillDescriptionForCalculation(otherChef, skills)
                val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
                
                // 检查"场上男性厨师稀有客人出现概率+*%"技能
                if (currentChefGender == 1) { // 当前厨师是男性
                    val maleChefPattern = "场上男性厨师稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
                    val maleChefMatches = maleChefPattern.findAll(combinedSkillDesc)
                    for (match in maleChefMatches) {
                        val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
                        if (value > 0) {
                            details.add(GuestRateDetail(
                                source = "场上技能：${otherChef.name}",
                                description = "场上男性厨师稀有客人出现概率+${value.toInt()}%",
                                value = value
                            ))
                        }
                    }
                }
                
                // 检查"场上女性厨师贵客率+*%"技能
                if (currentChefGender == 2) { // 当前厨师是女性
                    val femaleChefPattern = "场上女性厨师贵客率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
                    val femaleChefMatches = femaleChefPattern.findAll(combinedSkillDesc)
                    for (match in femaleChefMatches) {
                        val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
                        if (value > 0) {
                            details.add(GuestRateDetail(
                                source = "场上技能：${otherChef.name}",
                                description = "场上女性厨师贵客率+${value.toInt()}%",
                                value = value
                            ))
                        }
                    }
                }
            }
        }
    }
    
    return details
}

/**
 * 计算暴击率详细加成分解
 */
private fun calculateCritRateDetails(
    chef: com.example.show_auto.data.Chef,
    skills: List<com.example.show_auto.data.Skill>,
    gameData: com.example.show_auto.data.GameData?,
    personalData: com.example.show_auto.data.PersonalData?,
    defaultAllUltimate: Boolean = false
): List<GuestRateDetail> {
    val details = mutableListOf<GuestRateDetail>()
    
    // 1. 基础技能
    if (chef.skill > 0) {
        val baseSkill = skills.find { it.skillId == chef.skill }
        if (baseSkill != null) {
            val skillValue = extractCritRateFromSkill(baseSkill.desc)
            if (skillValue > 0) {
                details.add(GuestRateDetail(
                    source = "基础技能",
                    description = baseSkill.desc,
                    value = skillValue
                ))
            }
        }
    }
    
    // 2. 修炼技能
    val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(chef, skills, defaultAllUltimate)
    if (ultimateSkillDesc.isNotEmpty() && ultimateSkillDesc != "无修炼技能") {
        val skillValue = extractCritRateFromSkill(ultimateSkillDesc)
        if (skillValue > 0) {
            details.add(GuestRateDetail(
                source = "修炼技能",
                description = ultimateSkillDesc,
                value = skillValue
            ))
        }
    }
    
    // 3. 厨具加成
    if (personalData != null && gameData != null) {
        val pChef = personalData.chefs[chef.chefId]
        val equipId = pChef?.equip?.toString() ?: "0"
        val equip = gameData.equips.find { it.equipId == equipId }
        
        if (equip != null) {
            equip.skill.forEach { sid ->
                val skillObj = skills.find { it.skillId == sid }
                if (skillObj != null) {
                    val skillValue = extractCritRateFromSkill(skillObj.desc)
                    if (skillValue > 0) {
                        details.add(GuestRateDetail(
                            source = "厨具：${equip.name}",
                            description = skillObj.desc,
                            value = skillValue
                        ))
                    }
                }
            }
        }
    }
    
    return details
}

/**
 * 计算开业时间详细加成分解
 */
private fun calculateOpeningTimeDetails(
    chef: com.example.show_auto.data.Chef,
    skills: List<com.example.show_auto.data.Skill>,
    gameData: com.example.show_auto.data.GameData?,
    personalData: com.example.show_auto.data.PersonalData?,
    defaultAllUltimate: Boolean = false
): List<GuestRateDetail> {
    val details = mutableListOf<GuestRateDetail>()
    val openingTimePlusPattern = "开业时间\\+(\\d+(?:\\.\\d+)?)%".toRegex()
    val openingTimeMinusPattern = "开业时间-(\\d+(?:\\.\\d+)?)%".toRegex()
    
    // 1. 基础技能
    if (chef.skill > 0) {
        val baseSkill = skills.find { it.skillId == chef.skill }
        if (baseSkill != null) {
            // 检查开业时间+模式
            val plusMatches = openingTimePlusPattern.findAll(baseSkill.desc)
            for (match in plusMatches) {
                val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
                if (value > 0) {
                    details.add(GuestRateDetail(
                        source = "基础技能",
                        description = baseSkill.desc,
                        value = value
                    ))
                }
            }
            // 检查开业时间-模式
            val minusMatches = openingTimeMinusPattern.findAll(baseSkill.desc)
            for (match in minusMatches) {
                val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
                if (value > 0) {
                    details.add(GuestRateDetail(
                        source = "基础技能",
                        description = baseSkill.desc,
                        value = -value // 负值表示减少时间
                    ))
                }
            }
        }
    }
    
    // 2. 修炼技能
    val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(chef, skills, defaultAllUltimate)
    if (ultimateSkillDesc.isNotEmpty() && ultimateSkillDesc != "无修炼技能") {
        // 检查开业时间+模式
        val plusMatches = openingTimePlusPattern.findAll(ultimateSkillDesc)
        for (match in plusMatches) {
            val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
            if (value > 0) {
                details.add(GuestRateDetail(
                    source = "修炼技能",
                    description = ultimateSkillDesc,
                    value = value
                ))
            }
        }
        // 检查开业时间-模式
        val minusMatches = openingTimeMinusPattern.findAll(ultimateSkillDesc)
        for (match in minusMatches) {
            val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
            if (value > 0) {
                details.add(GuestRateDetail(
                    source = "修炼技能",
                    description = ultimateSkillDesc,
                    value = -value // 负值表示减少时间
                ))
            }
        }
    }
    
    // 3. 厨具加成
    if (personalData != null && gameData != null) {
        val pChef = personalData.chefs[chef.chefId]
        val equipId = pChef?.equip?.toString() ?: "0"
        val equip = gameData.equips.find { it.equipId == equipId }
        
        if (equip != null) {
            equip.skill.forEach { sid ->
                val skillObj = skills.find { it.skillId == sid }
                if (skillObj != null) {
                    // 检查开业时间+模式
                    val plusMatches = openingTimePlusPattern.findAll(skillObj.desc)
                    for (match in plusMatches) {
                        val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
                        if (value > 0) {
                            details.add(GuestRateDetail(
                                source = "厨具：${equip.name}",
                                description = skillObj.desc,
                                value = value
                            ))
                        }
                    }
                    // 检查开业时间-模式
                    val minusMatches = openingTimeMinusPattern.findAll(skillObj.desc)
                    for (match in minusMatches) {
                        val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
                        if (value > 0) {
                            details.add(GuestRateDetail(
                                source = "厨具：${equip.name}",
                                description = skillObj.desc,
                                value = -value // 负值表示减少时间
                            ))
                        }
                    }
                }
            }
        }
    }
    
    // 4. 心法盘加成
    if (personalData != null && gameData != null) {
        val pChef = personalData.chefs[chef.chefId]
        val diskLevel = (pChef?.dlv ?: 1).coerceAtLeast(1)
        val amberIds = pChef?.ambers ?: emptyList()
        
        if (amberIds.isNotEmpty()) {
            // 统计每个心法盘的数量和总加成
            val amberCountMap = mutableMapOf<String, Double>()
            
            amberIds.forEach { aid ->
                if (aid == 0) return@forEach
                val amber = gameData.ambers.find { it.amberId == aid.toString() }
                if (amber != null && amber.type == 3) { // 蓝色心法盘
                    val levelBonusEach = if (diskLevel > 1) amber.amplification * (diskLevel - 1) else 0
                    
                    amber.skill.forEach { sid ->
                        val skillObj = skills.find { it.skillId == sid }
                        if (skillObj != null) {
                            // 检查开业时间+模式
                            val plusMatches = openingTimePlusPattern.findAll(skillObj.desc)
                            for (match in plusMatches) {
                                val baseValue = match.groupValues[1].toDoubleOrNull() ?: 0.0
                                val totalValue = baseValue + levelBonusEach
                                if (totalValue > 0) {
                                    // 累加相同心法盘的加成值
                                    amberCountMap[amber.name] = amberCountMap.getOrDefault(amber.name, 0.0) + totalValue
                                }
                            }
                            // 检查开业时间-模式
                            val minusMatches = openingTimeMinusPattern.findAll(skillObj.desc)
                            for (match in minusMatches) {
                                val baseValue = match.groupValues[1].toDoubleOrNull() ?: 0.0
                                val totalValue = baseValue + levelBonusEach
                                if (totalValue > 0) {
                                    // 累加相同心法盘的加成值（负值）
                                    amberCountMap[amber.name] = amberCountMap.getOrDefault(amber.name, 0.0) - totalValue
                                }
                            }
                        }
                    }
                }
            }
            
            // 添加心法盘详情，显示为"心法盘名字X数量"格式
            amberCountMap.forEach { (amberName, totalValue) ->
                val count = amberIds.count { aid ->
                    if (aid == 0) return@count false
                    val amber = gameData.ambers.find { it.amberId == aid.toString() }
                    amber?.name == amberName && amber?.type == 3
                }
                val levelText = if (diskLevel > 1) " (${diskLevel}级)" else ""
                val displayName = if (count > 1) "${amberName}×${count}" else amberName
                val displayValue = if (totalValue > 0) "+${totalValue.toInt()}" else "${totalValue.toInt()}"
                details.add(GuestRateDetail(
                    source = "心法盘：${displayName}${levelText}",
                    description = "开业时间${displayValue}%",
                    value = totalValue
                ))
            }
        }
    }
    
    return details
}

/**
 * 获取蓝色心法盘数量
 */
private fun getBlueAmberCount(
    chef: com.example.show_auto.data.Chef,
    gameData: com.example.show_auto.data.GameData,
    personalData: com.example.show_auto.data.PersonalData
): Int {
    // 从厨师的diskDesc解析心法盘颜色
    val amberColors = if (chef.diskDesc.isNotEmpty()) {
        parseChefAmberColors(chef.diskDesc)
    } else {
        emptyList()
    }
    
    // 统计蓝色心法盘的数量
    return amberColors.count { it == "蓝" }
}

/**
 * 获取当前贵客率装备信息
 */
private fun getCurrentGuestRateEquipmentInfo(
    chef: com.example.show_auto.data.Chef,
    gameData: com.example.show_auto.data.GameData?,
    personalData: com.example.show_auto.data.PersonalData?,
    useMaxLevelAmber: Boolean = false
): String {
    if (gameData == null || personalData == null) return ""
    
    val pChef = personalData.chefs[chef.chefId] ?: return ""
    val equipParts = mutableListOf<String>()
    
    // 厨具信息
    val equipId = pChef.equip?.toString() ?: "0"
    val equip = gameData.equips.find { it.equipId == equipId }
    if (equip != null && equip.name.isNotEmpty()) {
        equipParts.add("厨具：${equip.name}")
    }
    
    // 蓝色心法盘信息
    val blueAmberNames = if (useMaxLevelAmber) {
        // 使用满朋陨配置
        val bluePositions = getBlueAmberPositions(chef)
        val maxLevelPengYun = gameData.ambers.find { amber ->
            amber.type == 3 && amber.name == "满朋陨"
        }
        if (maxLevelPengYun != null && bluePositions.isNotEmpty()) {
            List(bluePositions.size) { maxLevelPengYun.name }
        } else {
            emptyList()
        }
    } else {
        // 使用个人数据中的心法盘
        val amberIds = pChef.ambers ?: emptyList()
        amberIds.mapNotNull { aid ->
            if (aid == 0) return@mapNotNull null
            val amber = gameData.ambers.find { it.amberId == aid.toString() }
            if (amber?.type == 3) amber.name else null
        }
    }
    
    if (blueAmberNames.isNotEmpty()) {
        // 统计每个心法盘的数量
        val amberCountMap = blueAmberNames.groupingBy { it }.eachCount()
        val amberDisplayList = amberCountMap.map { (name, count) ->
            if (count > 1) "$name×$count" else name
        }
        equipParts.add("心法盘：${amberDisplayList.joinToString("、")}")
    }
    
    return equipParts.joinToString("｜")
}

/**
 * 贵客率详情内容 - 完全复刻暴击详情的样式
 */
@Composable
private fun GuestRateDetailsContent(
    chef: com.example.show_auto.data.Chef,
    skills: List<com.example.show_auto.data.Skill>,
    gameData: com.example.show_auto.data.GameData?,
    personalData: com.example.show_auto.data.PersonalData?,
    otherSelectedChefs: List<com.example.show_auto.data.Chef> = emptyList(),
    defaultMaxLevelAmber: Boolean = false,
    defaultAllUltimate: Boolean = false
) {
    if (gameData == null) {
        Text(
            text = "数据加载中...",
            modifier = Modifier.fillMaxWidth(),
            textAlign = androidx.compose.ui.text.style.TextAlign.Center
        )
        return
    }
    
    // 计算贵客率详情数据
    val guestRateDetails = calculateGuestRateDetails(chef, skills, gameData, personalData, otherSelectedChefs, defaultMaxLevelAmber, defaultAllUltimate)
    // 计算开业时间详情数据
    val openingTimeDetails = calculateOpeningTimeDetails(chef, skills, gameData, personalData, defaultAllUltimate)
    // 计算暴击率详情数据
    val critRateDetails = calculateCritRateDetails(chef, skills, gameData, personalData, defaultAllUltimate)
    
    Column(
        verticalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        // 贵客率加成行 - 使用与暴击详情相同的样式
        if (guestRateDetails.isNotEmpty()) {
            GuestRateDetailRow(
                guestRateDetails = guestRateDetails,
                isGuestRate = true
            )
        }
        
        // 暴击率加成行
        if (critRateDetails.isNotEmpty()) {
            GuestRateDetailRow(
                guestRateDetails = critRateDetails,
                isGuestRate = false,
                isCritRate = true
            )
        }
        
        // 开业时间加成行
        if (openingTimeDetails.isNotEmpty()) {
            GuestRateDetailRow(
                guestRateDetails = openingTimeDetails,
                isGuestRate = false,
                isCritRate = false
            )
        }
    }
    
    HorizontalDivider()
    
    // 说明文字
    Text(
        text = " ",
        fontSize = 10.sp,
        color = MaterialTheme.colorScheme.onSurfaceVariant,
        textAlign = androidx.compose.ui.text.style.TextAlign.Center,
        modifier = Modifier.fillMaxWidth(),
        maxLines = 1,
        overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis
    )
}

/**
 * 贵客率详情行 - 完全复刻暴击详情行的样式
 */
@Composable
private fun GuestRateDetailRow(
    guestRateDetails: List<GuestRateDetail>,
    isGuestRate: Boolean = true,
    isCritRate: Boolean = false
) {
    val skillValue = guestRateDetails.filter { 
        it.source.contains("基础技能") || it.source.contains("修炼技能") 
    }.sumOf { it.value }.toInt()
    
    val equipValue = guestRateDetails.filter { 
        it.source.contains("厨具") 
    }.sumOf { it.value }.toInt()
    
    val amberValue = guestRateDetails.filter { 
        it.source.contains("心法盘") 
    }.sumOf { it.value }.toInt()
    
    // 获取场上技能的详细信息
    val fieldSkillDetails = guestRateDetails.filter { 
        it.source.contains("场上技能") 
    }
    val fieldSkillValue = fieldSkillDetails.sumOf { it.value }.toInt()
    
    val total = guestRateDetails.sumOf { it.value }.toInt()
    val color = when {
        isGuestRate -> Color(0xFF7B1FA2) // 贵客率用紫色
        isCritRate -> Color(0xFFE91E63)   // 暴击率用粉色
        else -> Color(0xFF4CAF50)         // 开业时间用绿色
    }
    
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .height(IntrinsicSize.Min) // 让Row高度自适应内容
            .background(
                color = color.copy(alpha = 0.1f),
                shape = RoundedCornerShape(8.dp)
            )
            .padding(8.dp),
        verticalAlignment = Alignment.Top,
        horizontalArrangement = Arrangement.Start
    ) {
        // 类型标识 - 复刻暴击详情的图标样式
        Box(
            modifier = Modifier
                .width(26.dp)
                .fillMaxHeight() // 填充Row的高度
                .background(
                    color = color,
                    shape = RoundedCornerShape(4.dp)
                )
                .padding(vertical = 2.dp), // 添加少量垂直内边距
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = when {
                    isGuestRate -> "贵客"
                    isCritRate -> "暴击"
                    else -> "时间"
                },
                fontSize = 10.sp,
                fontWeight = FontWeight.Bold,
                color = Color.White
            )
        }
        
        Spacer(modifier = Modifier.width(8.dp))
        
        // 数值显示 - 完全复刻暴击详情的格式
        Column(
            modifier = Modifier.weight(1f)
        ) {
            // 构建来源详情文本
            val parts = mutableListOf<String>()
            if (skillValue != 0) parts.add("技能${if (skillValue > 0) "+$skillValue" else "$skillValue"}")
            if (equipValue != 0) parts.add("厨具${if (equipValue > 0) "+$equipValue" else "$equipValue"}")
            if (amberValue != 0) parts.add("心法盘${if (amberValue > 0) "+$amberValue" else "$amberValue"}")
            
            // 处理场上技能，显示具体的厨师名称
            if (fieldSkillDetails.isNotEmpty()) {
                val fieldSkillParts = fieldSkillDetails.map { detail ->
                    // 从 "场上技能：厨师名称" 中提取厨师名称
                    val chefName = detail.source.substringAfter("场上技能：")
                    val value = detail.value.toInt()
                    "$chefName${if (value > 0) "+$value" else "$value"}"
                }
                parts.addAll(fieldSkillParts)
            }
            
            when {
                parts.isEmpty() -> {
                    // 无加成时只显示总值
                    Text(
                        text = "${if (total > 0) "+$total" else "$total"}%",
                        fontSize = 11.sp,
                        fontWeight = FontWeight.Bold,
                        color = if (total != 0) color else MaterialTheme.colorScheme.onSurfaceVariant,
                        overflow = androidx.compose.ui.text.style.TextOverflow.Visible
                    )
                }
                parts.size == 1 -> {
                    // 只有一个来源时，直接显示"来源X%"
                    Text(
                        text = "${parts[0]}%",
                        fontSize = 11.sp,
                        fontWeight = FontWeight.Bold,
                        color = color,
                        overflow = androidx.compose.ui.text.style.TextOverflow.Visible
                    )
                }
                else -> {
                    // 多个来源时，显示详细分解
                    Text(
                        text = "${parts.joinToString(" + ")} = ${if (total > 0) "+$total" else "$total"}%",
                        fontSize = 11.sp,
                        fontWeight = FontWeight.Bold,
                        color = color,
                        overflow = androidx.compose.ui.text.style.TextOverflow.Visible
                    )
                }
            }
        }
    }
}



/**
 * 获取厨具拥有状态
 */
private fun getEquipOwnershipStatus(equip: com.example.show_auto.data.Equip, allRecipes: List<com.example.show_auto.data.Recipe>): EquipOwnershipStatus {
    // 拆分厨具的所有来源
    val equipOrigins = equip.origin.replace("<br>", "、").split("、").map { it.trim() }
    
    // 检查是否包含奖池来源
    val hasPoolOrigin = equipOrigins.any { origin ->
        origin.contains("新手奖池") || 
        origin.contains("中级奖池") || 
        origin.contains("高级奖池") || 
        origin.contains("碧池")
    }
    
    if (hasPoolOrigin) {
        return EquipOwnershipStatus(
            text = "已拥有",
            color = androidx.compose.ui.graphics.Color(0xFF1976D2) // 蓝色，与厨具技法一致
        )
    }

    // 检查是否包含默认可能拥有的来源
    val hasDefaultPossibleOrigin = equipOrigins.any { origin ->
        origin.contains("实验室") || origin.contains("厨神")
    }
    
    // 检查是否有已获得的菜谱来源包含厨具任一来源（需要5个及以上）
    val hasMatchingRecipeOrigin = equipOrigins.any { equipOrigin ->
        val matchingRecipeCount = allRecipes.count { recipe ->
            recipe.got && recipe.origin.contains(equipOrigin)
        }
        matchingRecipeCount >= 5
    }

    return if (hasDefaultPossibleOrigin || hasMatchingRecipeOrigin) {
        EquipOwnershipStatus(
            text = "可能已有",
            color = androidx.compose.ui.graphics.Color(0xFFFFC107) // 黄色
        )
    } else {
        EquipOwnershipStatus(
            text = "未拥有",
            color = androidx.compose.ui.graphics.Color(0xFFF44336) // 红色
        )
    }
}

/**
 * 计算开业时间加成，使用指定的厨具
 * @param chef 厨师数据
 * @param equip 指定的厨具（可以为null）
 * @param skills 技能数据列表
 * @param gameData 游戏数据（用于获取心法盘信息）
 * @param personalData 个人数据（用于获取心法盘信息）
 * @return 开业时间加成百分比，正值表示减少时间，负值表示增加时间
 */
private fun calculateOpeningTimeBonus(
    chef: com.example.show_auto.data.Chef, 
    equip: com.example.show_auto.data.Equip?,
    skills: List<com.example.show_auto.data.Skill>,
    gameData: com.example.show_auto.data.GameData? = null,
    personalData: com.example.show_auto.data.PersonalData? = null,
    defaultAllUltimate: Boolean = false
): Double {
    var totalBonus = 0.0
    
    // 1. 计算厨师技能开业时间加成
    // 获取基础技能描述
    val baseSkillDesc = if (chef.skill > 0) {
        skills.find { it.skillId == chef.skill }?.desc ?: ""
    } else {
        ""
    }
    
    // 获取修炼技能描述
    val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(chef, skills, defaultAllUltimate)
    
    // 合并厨师技能描述
    val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
    
    // 匹配开业时间相关的技能，分别处理减号和加号
    val openingTimeMinusPattern = "开业时间-(\\d+(?:\\.\\d+)?)%".toRegex()
    val openingTimePlusPattern = "开业时间\\+(\\d+(?:\\.\\d+)?)%".toRegex()
    
    // 从厨师技能中提取开业时间加成
    // 处理减号（-）的情况，减少时间
    val minusMatches = openingTimeMinusPattern.findAll(combinedSkillDesc)
    for (match in minusMatches) {
        val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
        totalBonus -= value // 减号表示减少时间，所以是负值
    }
    
    // 处理加号（+）的情况，增加时间
    val plusMatches = openingTimePlusPattern.findAll(combinedSkillDesc)
    for (match in plusMatches) {
        val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
        totalBonus += value // 加号表示增加时间，所以是正值
    }
    
    // 如果没有游戏数据或个人数据，返回厨师技能加成
    if (gameData == null || personalData == null) {
        return totalBonus
    }
    
    // 2. 计算厨具开业时间加成（使用传入的equip参数）
    if (equip != null) {
        // 检查厨师是否有厨具技法效果翻倍技能
        val hasEquipSkillMultiplier = hasEquipSkillMultiplier(chef, skills)
        val multiplier = if (hasEquipSkillMultiplier) 2.0 else 1.0
        
        // 遍历厨具的所有技能
        for (skillId in equip.skill) {
            val skill = skills.find { it.skillId == skillId }
            if (skill != null) {
                // 处理减号（-）的情况
                val equipMinusMatches = openingTimeMinusPattern.findAll(skill.desc)
                for (equipMatch in equipMinusMatches) {
                    val value = equipMatch.groupValues[1].toDoubleOrNull() ?: 0.0
                    totalBonus -= value * multiplier // 减号表示减少时间，所以是负值
                }
                
                // 处理加号（+）的情况
                val equipPlusMatches = openingTimePlusPattern.findAll(skill.desc)
                for (equipMatch in equipPlusMatches) {
                    val value = equipMatch.groupValues[1].toDoubleOrNull() ?: 0.0
                    totalBonus += value * multiplier // 加号表示增加时间，所以是正值
                }
            }
        }
    }
    
    // 3. 计算心法盘开业时间加成
    val pChef = personalData.chefs[chef.chefId]
    val diskLevel = (pChef?.dlv ?: 1).coerceAtLeast(1)
    val amberIds = pChef?.ambers ?: emptyList()
    
    if (amberIds.isNotEmpty()) {
        amberIds.forEach { aid ->
            if (aid == 0) return@forEach
            val amber = gameData.ambers.find { it.amberId == aid.toString() }
            if (amber != null) {
                val levelBonusEach = if (diskLevel > 1) amber.amplification * (diskLevel - 1) else 0
                
                // 遍历心法盘的所有技能
                amber.skill.forEach { sid ->
                    val skillObj = skills.find { it.skillId == sid }
                    if (skillObj != null) {
                        // 处理减号（-）的情况
                        val amberMinusMatches = openingTimeMinusPattern.findAll(skillObj.desc)
                        for (amberMatch in amberMinusMatches) {
                            val baseValue = amberMatch.groupValues[1].toDoubleOrNull() ?: 0.0
                            val totalValue = baseValue + levelBonusEach
                            totalBonus -= totalValue // 减号表示减少时间，所以是负值
                        }
                        
                        // 处理加号（+）的情况
                        val amberPlusMatches = openingTimePlusPattern.findAll(skillObj.desc)
                        for (amberMatch in amberPlusMatches) {
                            val baseValue = amberMatch.groupValues[1].toDoubleOrNull() ?: 0.0
                            val totalValue = baseValue + levelBonusEach
                            totalBonus += totalValue // 加号表示增加时间，所以是正值
                        }
                    }
                }
            }
        }
    }
    
    return totalBonus
}

/**
 * 格式化百分比显示，保留小数点精度
 * @param value 数值
 * @return 格式化后的字符串，整数显示整数，小数显示一位小数
 */
private fun formatPercentage(value: Double): String {
    return if (value % 1.0 == 0.0) {
        value.toInt().toString()
    } else {
        String.format("%.1f", value)
    }
}

// 辅助函数：获取菜谱技法文本
private fun getRecipeSkillText(recipe: com.example.show_auto.data.Recipe): String {
    val skills = mutableListOf<String>()

    if (recipe.stirfry > 0) skills.add("炒${recipe.stirfry}")
    if (recipe.boil > 0) skills.add("煮${recipe.boil}")
    if (recipe.knife > 0) skills.add("切${recipe.knife}")
    if (recipe.fry > 0) skills.add("炸${recipe.fry}")
    if (recipe.bake > 0) skills.add("烤${recipe.bake}")
    if (recipe.steam > 0) skills.add("蒸${recipe.steam}")

    return skills.joinToString(" ")
}

// 辅助函数：获取技法差值文本
private fun getSkillGapText(chef: com.example.show_auto.data.Chef, recipe: com.example.show_auto.data.Recipe): Pair<String, List<Pair<String, Boolean>>> {
    // 计算厨师当前技法值与神级要求（4倍菜谱需求）的差值
    val gaps = mutableListOf<Pair<String, Boolean>>() // Boolean表示是否为负值（红色显示）
    
    if (recipe.stirfry > 0) {
        val godTierRequirement = recipe.stirfry * 4 // 神级需要4倍菜谱需求
        val gap = chef.stirfry - godTierRequirement
        if (gap < 0) {
            gaps.add("炒${gap}" to true) // 负值，红色显示
        } else {
            gaps.add("炒${recipe.stirfry}" to false) // 技法充足时显示菜谱基础需求
        }
    }
    
    if (recipe.boil > 0) {
        val godTierRequirement = recipe.boil * 4
        val gap = chef.boil - godTierRequirement
        if (gap < 0) {
            gaps.add("煮${gap}" to true)
        } else {
            gaps.add("煮${recipe.boil}" to false)
        }
    }
    
    if (recipe.knife > 0) {
        val godTierRequirement = recipe.knife * 4
        val gap = chef.knife - godTierRequirement
        if (gap < 0) {
            gaps.add("切${gap}" to true)
        } else {
            gaps.add("切${recipe.knife}" to false)
        }
    }
    
    if (recipe.fry > 0) {
        val godTierRequirement = recipe.fry * 4
        val gap = chef.fry - godTierRequirement
        if (gap < 0) {
            gaps.add("炸${gap}" to true)
        } else {
            gaps.add("炸${recipe.fry}" to false)
        }
    }
    
    if (recipe.bake > 0) {
        val godTierRequirement = recipe.bake * 4
        val gap = chef.bake - godTierRequirement
        if (gap < 0) {
            gaps.add("烤${gap}" to true)
        } else {
            gaps.add("烤${recipe.bake}" to false)
        }
    }
    
    if (recipe.steam > 0) {
        val godTierRequirement = recipe.steam * 4
        val gap = chef.steam - godTierRequirement
        if (gap < 0) {
            gaps.add("蒸${gap}" to true)
        } else {
            gaps.add("蒸${recipe.steam}" to false)
        }
    }
    
    val displayText = gaps.map { it.first }.joinToString(" ")
    return displayText to gaps
}

// 辅助函数：检查菜谱是否包含指定技法
private fun hasRequiredSkill(recipe: com.example.show_auto.data.Recipe, skillType: String): Boolean {
    return when (skillType.lowercase()) {
        "knife" -> recipe.knife > 0
        "stirfry" -> recipe.stirfry > 0
        "boil" -> recipe.boil > 0
        "fry" -> recipe.fry > 0
        "bake" -> recipe.bake > 0
        "steam" -> recipe.steam > 0
        else -> false
    }
}

/**
 * 解析厨师的心法盘颜色配置
 * @param diskDesc 心法盘配置描述，如"蓝|绿|绿<br>最高5级"
 * @return 心法盘颜色列表，如["蓝", "绿", "绿"]
 */
private fun parseChefAmberColors(diskDesc: String): List<String> {
    if (diskDesc.isEmpty()) return emptyList()
    
    // 解析类似 "蓝|绿|绿<br>最高5级" 的格式
    val diskTypes = diskDesc.split("<br>")[0] // 取第一部分，去掉等级描述
    val types = diskTypes.split("|")
    
    return types.map { it.trim() }
}

/**
 * 获取厨师蓝色心法盘的位置索引
 * @param chef 厨师数据
 * @return 蓝色心法盘位置的索引列表，如果没有蓝色心法盘则返回空列表
 */
private fun getBlueAmberPositions(chef: com.example.show_auto.data.Chef): List<Int> {
    val amberColors = parseChefAmberColors(chef.diskDesc)
    val bluePositions = mutableListOf<Int>()
    amberColors.forEachIndexed { index, color ->
        if (color == "蓝") {
            bluePositions.add(index)
        }
    }
    
    // 调试信息：输出心法盘颜色解析结果
    System.out.println("  厨师 ${chef.name} 的心法盘描述: ${chef.diskDesc}")
    System.out.println("  解析出的心法盘颜色: $amberColors")
    System.out.println("  蓝色心法盘位置: $bluePositions")
    
    return bluePositions
}

/**
 * 应用满朋陨到指定厨师的蓝色心法盘位置
 * @param chef 厨师数据
 * @param currentAmbers 当前心法盘配置
 * @param gameData 游戏数据
 * @param useMaxLevelAmber 是否使用满朋陨
 * @return 更新后的心法盘配置
 */
private fun applyMaxLevelAmberToBluePositions(
    chef: com.example.show_auto.data.Chef,
    currentAmbers: MutableList<com.example.show_auto.data.Amber?>,
    gameData: com.example.show_auto.data.GameData?,
    useMaxLevelAmber: Boolean
): List<com.example.show_auto.data.Amber?> {
    if (!useMaxLevelAmber || gameData == null) {
        return currentAmbers
    }
    
    // 查找满朋陨
    val maxLevelPengYun = gameData.ambers.find { amber ->
        amber.type == 3 && amber.name == "满朋陨"
    }
    
    if (maxLevelPengYun != null) {
        // 获取蓝色心法盘位置并应用满朋陨
        val bluePositions = getBlueAmberPositions(chef)
        System.out.println("  厨师 ${chef.name} 的蓝色心法盘位置: $bluePositions")
        System.out.println("  找到满朋陨: ${maxLevelPengYun.name} (ID: ${maxLevelPengYun.amberId})")
        
        bluePositions.forEach { position ->
            if (position < currentAmbers.size) {
                currentAmbers[position] = maxLevelPengYun
                System.out.println("    在位置 $position 应用满朋陨")
            }
        }
    } else {
        System.out.println("  未找到满朋陨心法盘")
    }
    
    return currentAmbers
}

/**
 * 根据心法盘颜色筛选对应颜色的心法盘数据
 * @param ambers 所有心法盘数据
 * @param color 心法盘颜色（"红"、"绿"、"蓝"）
 * @return 对应颜色的心法盘列表
 */
private fun filterAmbersByColor(ambers: List<com.example.show_auto.data.Amber>, color: String): List<com.example.show_auto.data.Amber> {
    val colorType = when (color) {
        "红" -> 1
        "绿" -> 2
        "蓝" -> 3
        else -> 0
    }
    
    return ambers.filter { it.type == colorType }
}

/**
 * 贵客率计算器专用心法盘选择框
 */
@Composable
private fun CalculatorAmberBox(
    amber: com.example.show_auto.data.Amber?,
    amberColor: String,
    availableAmbers: List<com.example.show_auto.data.Amber>,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .height(DeviceCompatibility.getAdaptiveHeight(60.dp))
            .clickable { onClick() },
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surface
        ),
        border = BorderStroke(
            width = 1.dp,
            color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f)
        )
    ) {
        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            if (amber != null && amber.name.isNotEmpty()) {
                // 显示心法盘信息
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(4.dp),
                    verticalArrangement = Arrangement.spacedBy(2.dp)
                ) {
                    // 第一行：心法盘名称和星级
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = amber.name,
                            fontSize = 8.sp,
                            fontWeight = FontWeight.Bold,
                            color = MaterialTheme.colorScheme.primary,
                            maxLines = 1,
                            modifier = Modifier.weight(1f)
                        )

                        Spacer(modifier = Modifier.width(2.dp))

                        // 星级显示
                        repeat(amber.rarity) {
                            Icon(
                                imageVector = Icons.Default.Star,
                                contentDescription = null,
                                tint = MaterialTheme.colorScheme.primary,
                                modifier = Modifier.size(6.dp)
                            )
                        }
                    }
                    
                    // 第二行：技能描述
                    if (amber.desc.isNotEmpty()) {
                        Text(
                            text = amber.desc,
                            fontSize = 7.sp,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            maxLines = 2,
                            lineHeight = 8.sp
                        )
                    }
                    
                    // 第三行：来源信息
                    if (amber.origin.isNotEmpty()) {
                        Text(
                            text = amber.origin,
                            fontSize = 6.sp,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            maxLines = 1,
                            lineHeight = 7.sp
                        )
                    }
                }
            } else {
                // 心法盘占位符
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.spacedBy(2.dp)
                ) {
                                            Text(
                            text = if (amberColor == "绿") "不可选" else if (amberColor.isNotEmpty()) "+ ${amberColor}心法盘" else "+ 心法盘",
                            fontSize = 8.sp,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    if (availableAmbers.isNotEmpty()) {
                        Text(
                            text = "(${availableAmbers.size}个可选)",
                            fontSize = 6.sp,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
            }
        }
    }
}

/**
 * 贵客率计算器专用心法盘下拉选择框
 */
@Composable
private fun CalculatorAmberDropdown(
    amber: com.example.show_auto.data.Amber?,
    amberColor: String,
    availableAmbers: List<com.example.show_auto.data.Amber>,
    onAmberSelected: (com.example.show_auto.data.Amber) -> Unit,
    onClearAmber: () -> Unit,
    enabled: Boolean = true,
    chef: com.example.show_auto.data.Chef? = null,
    amberIndex: Int = 0,
    useMaxLevelAmber: Boolean = false,
    gameData: com.example.show_auto.data.GameData? = null,
    modifier: Modifier = Modifier
) {
    var expanded by remember { mutableStateOf(false) }
    var cardWidth by remember { mutableStateOf(0.dp) }
    val density = LocalDensity.current
    
    // 过滤心法盘列表 - 只展示技能带有稀有客人或江湖帖的心法盘
                val filteredAmbers = remember(availableAmbers) {
                availableAmbers.filter { amber ->
                    // 根据心法盘颜色筛选不同类型的心法盘
                    when (amberColor) {
                        "红" -> amber.desc.contains("技法+") // 红色心法盘：技法加成
                        "绿" -> amber.desc.contains("稀有客人") // 绿色心法盘：稀有客人
                        "蓝" -> amber.desc.contains("稀有客人") // 蓝色心法盘：稀有客人
                        else -> false
                    }
                }.sortedWith { amber1, amber2 ->
                    // 首先按描述类型分组
                    val getDescType = { amber: com.example.show_auto.data.Amber ->
                        when {
                            amber.desc.contains("稀有客人") -> 0
                            amber.desc.contains("技法+") -> 1
                            else -> 2
                        }
                    }
            
                    val typeComparison = getDescType(amber1).compareTo(getDescType(amber2))
                    if (typeComparison != 0) {
                        typeComparison
                    } else if (amberColor == "红") {
                        // 红色心法盘：按技法类型分组，然后按星级和名称排序
                        val getTechniqueType = { amber: com.example.show_auto.data.Amber ->
                            when {
                                amber.desc.contains("炒技法+") -> 0
                                amber.desc.contains("煮技法+") -> 1
                                amber.desc.contains("切技法+") -> 2
                                amber.desc.contains("炸技法+") -> 3
                                amber.desc.contains("烤技法+") -> 4
                                amber.desc.contains("蒸技法+") -> 5
                                else -> 6 // 其他技法或混合技法
                            }
                        }
                        
                        val techniqueComparison = getTechniqueType(amber1).compareTo(getTechniqueType(amber2))
                        if (techniqueComparison != 0) {
                            techniqueComparison
                        } else {
                            // 同技法类型内按星级降序排序
                            val rarityComparison = amber2.rarity.compareTo(amber1.rarity)
                            if (rarityComparison != 0) {
                                rarityComparison
                            } else {
                                // 同星级按名称排序
                                amber1.name.compareTo(amber2.name)
                            }
                        }
                    } else {
                        // 其他颜色心法盘：按星级降序排序
                        val rarityComparison = amber2.rarity.compareTo(amber1.rarity)
                        if (rarityComparison != 0) {
                            rarityComparison
                        } else {
                            // 同星级按名称排序
                            amber1.name.compareTo(amber2.name)
                        }
                    }
                }
    }
    
    Box(modifier = modifier) {
        // 下拉框触发器
        OutlinedCard(
            modifier = Modifier
                .fillMaxWidth()
                .clickable(enabled = enabled) { expanded = true }
                .onGloballyPositioned { coordinates ->
                    cardWidth = with(density) { coordinates.size.width.toDp() }
                },
            border = BorderStroke(
                width = 1.dp,
                color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f)
            ),
            shape = RoundedCornerShape(4.dp),
            colors = CardDefaults.outlinedCardColors(
                containerColor = if (amberColor.isNotEmpty()) {
                    when (amberColor) {
                        "红" -> Color(0xFFFFE0E0) // 浅红色背景
                        "绿" -> Color(0xFFE0FFE0) // 浅绿色背景
                        "蓝" -> Color(0xFFE0E0FF) // 浅蓝色背景
                        else -> MaterialTheme.colorScheme.surface
                    }
                } else {
                    MaterialTheme.colorScheme.surface
                }
            )
        ) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(4.dp)
            ) {
                                Box(
                    modifier = Modifier.fillMaxWidth(),
                    contentAlignment = Alignment.Center
                ) {
                    if (amberColor == "绿") {
                        // 绿色心法盘位置统一显示"不可选"，无论是否已佩戴
                        Text(
                            text = "不可选",
                            fontSize = 10.sp,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    } else if (amber != null) {
                        // 显示已选择的心法盘 - 始终显示用户实际选择的心法盘名称
                        val displayName = amber.name
                        
                        Text(
                            text = displayName,
                            fontSize = 10.sp,
                            fontWeight = FontWeight.Medium,
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis
                        )
                    } else {
                        // 显示占位符
                        Text(
                            text = "+ 遗玉",
                            fontSize = 10.sp,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
            }
        }
        
                         // 下拉菜单
        DropdownMenu(
            expanded = expanded,
            onDismissRequest = { expanded = false },
            modifier = Modifier
                .width(cardWidth)
                .heightIn(max = 200.dp)
        ) {
            
                         // 清空选项
             Box(
                 modifier = Modifier
                     .fillMaxWidth()
                     .height(23.dp)
                     .padding(horizontal = 8.dp, vertical = 0.dp)
                     .background(
                         Color.White,
                         RoundedCornerShape(4.dp)
                     )
                     .border(
                         1.dp,
                         Color.Black,
                         RoundedCornerShape(4.dp)
                     )
                     .clickable { onClearAmber() },
                 contentAlignment = Alignment.Center
             ) {
                 Text(
                     text = "清空",
                     fontSize = 9.sp,
                     color = Color.Black
                 )
             }
            
            HorizontalDivider()
            
            // 心法盘列表
            if (filteredAmbers.isEmpty()) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(28.dp)
                        .padding(horizontal = 8.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "无",
                        fontSize = 10.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            } else {
                filteredAmbers.forEachIndexed { index, availableAmber ->
                                    Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(28.dp)
                        .clickable {
                            onAmberSelected(availableAmber)
                            expanded = false
                        }
                        .padding(horizontal = 8.dp),
                    contentAlignment = Alignment.Center
                ) {
                        Text(
                            text = availableAmber.name,
                            fontSize = 9.sp,
                            fontWeight = FontWeight.Medium
                        )
                    }
                    
                    // 在每个心法盘之间添加横线分隔（除了最后一个）
                    if (index < filteredAmbers.size - 1) {
                        HorizontalDivider(
                            modifier = Modifier.padding(horizontal = 8.dp),
                            color = MaterialTheme.colorScheme.outline,
                            thickness = 0.5.dp
                        )
                    }
                }
            }
        }
    }
}

/**
 * 贵客率计算器专用等级下拉选择框
 */
@Composable
private fun CalculatorLevelDropdown(
    levels: List<Int>,
    selectedLevel: Int?,
    onLevelSelected: (Int) -> Unit,
    chef: com.example.show_auto.data.Chef? = null,
    personalData: com.example.show_auto.data.PersonalData? = null,
    useMaxLevelAmber: Boolean = false,
    modifier: Modifier = Modifier
) {
    var expanded by remember { mutableStateOf(false) }
    var cardWidth by remember { mutableStateOf(0.dp) }
    val density = LocalDensity.current
    
    Box(modifier = modifier) {
        // 下拉框触发器
        OutlinedCard(
            modifier = Modifier
                .fillMaxWidth()
                .clickable { expanded = true }
                .onGloballyPositioned { coordinates ->
                    cardWidth = with(density) { coordinates.size.width.toDp() }
                },
            border = BorderStroke(
                width = 1.dp,
                color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f)
            ),
            shape = RoundedCornerShape(4.dp)
        ) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(4.dp)
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    // 在展开按钮左侧区域居中显示等级
                    Box(
                        modifier = Modifier.weight(1f),
                        contentAlignment = Alignment.Center
                    ) {
                        // 始终显示用户实际选择的等级，如果没有选择则显示默认值
                        val displayLevel = selectedLevel ?: 1
                        
                        Text(
                            text = "${displayLevel}级",
                            fontSize = 10.sp,
                            fontWeight = FontWeight.Medium,
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis
                        )
                    }
                    
                    // 下拉箭头
                    Icon(
                        imageVector = Icons.Default.ArrowDropDown,
                        contentDescription = "展开",
                        tint = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.size(16.dp)
                    )
                }
            }
        }
        
        // 下拉菜单
        DropdownMenu(
            expanded = expanded,
            onDismissRequest = { expanded = false },
            modifier = Modifier
                .width(cardWidth)
                .heightIn(max = 200.dp)
        ) {
            // 清空选项
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(23.dp)
                    .padding(horizontal = 8.dp, vertical = 0.dp)
                    .background(
                        Color.White,
                        RoundedCornerShape(4.dp)
                    )
                    .border(
                        1.dp,
                        Color.Black,
                        RoundedCornerShape(4.dp)
                    )
                    .clickable { 
                        // 重置为个人数据中当前厨师的心法盘等级，如果没有则使用默认等级
                        val resetLevel = if (chef != null && personalData != null) {
                            val personalChef = personalData.chefs[chef.chefId]
                            personalChef?.dlv ?: when (chef.rarity) {
                                5 -> 5
                                4 -> 4
                                else -> 3
                            }
                        } else {
                            when (chef?.rarity) {
                                5 -> 5
                                4 -> 4
                                else -> 3
                            }
                        }
                        onLevelSelected(resetLevel)
                        expanded = false 
                    },
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = "重置",
                    fontSize = 9.sp,
                    color = Color.Black
                )
            }
            
            HorizontalDivider()
            
            // 等级列表
            levels.forEach { level ->
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(28.dp)
                        .clickable {
                            onLevelSelected(level)
                            expanded = false
                        }
                        .padding(horizontal = 16.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "${level}级",
                        fontSize = 9.sp,
                        fontWeight = FontWeight.Medium
                    )
                }
            }
        }
    }
}

/**
 * 计算厨师的总贵客率加成，使用计算器中选择的数据
 * @param chef 厨师数据
 * @param skills 技能数据列表
 * @param gameData 游戏数据（用于获取心法盘信息）
 * @param personalData 个人数据（用于获取心法盘信息）
 * @param selectedLevel 计算器中选择的等级
 * @param selectedAmbers 计算器中选择的心法盘列表
 * @return 总贵客率加成百分比，只计算基础的"稀有客人出现概率+X%"技能
 */
private fun calculateTotalGuestRateBonusWithCalculatorData(
    chef: com.example.show_auto.data.Chef,
    skills: List<com.example.show_auto.data.Skill>,
    gameData: com.example.show_auto.data.GameData?,
    personalData: com.example.show_auto.data.PersonalData?,
    selectedLevel: Int?,
    selectedAmbers: List<com.example.show_auto.data.Amber?>?,
    equip: com.example.show_auto.data.Equip? = null,
    defaultAllUltimate: Boolean = false
): Double {
    var totalBonus = 0.0
    
    // 1. 计算厨师技能加成
    // 获取基础技能描述
    val baseSkillDesc = if (chef.skill > 0) {
        skills.find { it.skillId == chef.skill }?.desc ?: ""
    } else {
        ""
    }
    
    // 获取修炼技能描述
    val ultimateSkillDesc = getChefSkillDescription(chef, skills)
    
    // 合并厨师技能描述
    val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
    
    // 计算厨师技能中的贵客率加成
    totalBonus += calculateChefSkillGuestRateBonus(combinedSkillDesc, chef)
    
    // 定义贵客率正则表达式（用于厨具和心法盘）
    val guestRatePattern = "稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
    
    // 2. 计算厨具加成
    if (equip != null) {
        // 检查厨师是否有厨具技法效果翻倍技能
        val hasEquipSkillMultiplier = hasEquipSkillMultiplier(chef, skills)
        val multiplier = if (hasEquipSkillMultiplier) 2.0 else 1.0
        
        // 遍历厨具的所有技能
        for (skillId in equip.skill) {
            val skill = skills.find { it.skillId == skillId }
            if (skill != null) {
                val equipMatches = guestRatePattern.findAll(skill.desc)
                for (equipMatch in equipMatches) {
                    val value = equipMatch.groupValues[1].toDoubleOrNull() ?: 0.0
                    totalBonus += value * multiplier
                }
            }
        }
    }
    
    // 3. 计算心法盘加成（使用计算器中选择的数据）
    if (selectedAmbers != null && gameData != null) {
        val diskLevel = selectedLevel ?: when (chef.rarity) {
            5 -> 5
            4 -> 4
            else -> 3
        }
        
        selectedAmbers.forEach { amber ->
            if (amber != null && amber.type == 3) { // 蓝色心法盘（贵客率相关）
                val levelBonusEach = if (diskLevel > 1) amber.amplification * (diskLevel - 1) else 0
                
                // 遍历心法盘的所有技能
                amber.skill.forEach { skillId ->
                    val skill = skills.find { it.skillId == skillId }
                    if (skill != null) {
                        val amberMatches = guestRatePattern.findAll(skill.desc)
                        for (amberMatch in amberMatches) {
                            val baseValue = amberMatch.groupValues[1].toDoubleOrNull() ?: 0.0
                            val totalValue = baseValue + levelBonusEach
                            totalBonus += totalValue
                        }
                    }
                }
            }
        }
    }
    
    return totalBonus
}

/**
 * 计算厨师的总暴击加成，使用计算器中选择的数据
 * @param chef 厨师数据
 * @param skills 技能数据列表
 * @param gameData 游戏数据（用于获取心法盘信息）
 * @param personalData 个人数据（用于获取心法盘信息）
 * @param selectedLevel 计算器中选择的等级
 * @param selectedAmbers 计算器中选择的心法盘列表
 * @return 总暴击加成百分比
 */
private fun calculateTotalCritRateBonusWithCalculatorData(
    chef: com.example.show_auto.data.Chef,
    skills: List<com.example.show_auto.data.Skill>,
    gameData: com.example.show_auto.data.GameData?,
    personalData: com.example.show_auto.data.PersonalData?,
    selectedLevel: Int?,
    selectedAmbers: List<com.example.show_auto.data.Amber?>?,
    equip: com.example.show_auto.data.Equip? = null
): Double {
    var totalBonus = 0.0
    
    // 1. 计算厨师技能加成
    // 获取基础技能描述
    val baseSkillDesc = if (chef.skill > 0) {
        skills.find { it.skillId == chef.skill }?.desc ?: ""
    } else {
        ""
    }
    
    // 获取修炼技能描述
    val ultimateSkillDesc = getChefSkillDescription(chef, skills)
    
    // 合并厨师技能描述
    val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
    
    // 计算各类暴击相关技能
    totalBonus += calculateCritBonusFromSkill(combinedSkillDesc)
    
    // 2. 计算厨具加成
    if (equip != null) {
        // 检查厨师是否有厨具技法效果翻倍技能
        val hasEquipSkillMultiplier = hasEquipSkillMultiplier(chef, skills)
        val multiplier = if (hasEquipSkillMultiplier) 2.0 else 1.0
        
        // 遍历厨具的所有技能
        for (skillId in equip.skill) {
            val skill = skills.find { it.skillId == skillId }
            if (skill != null) {
                totalBonus += calculateCritBonusFromSkill(skill.desc) * multiplier
            }
        }
    }
    
    // 3. 计算心法盘加成（使用计算器中选择的数据）
    if (selectedAmbers != null && gameData != null) {
        val diskLevel = selectedLevel ?: when (chef.rarity) {
            5 -> 5
            4 -> 4
            else -> 3
        }
        
        selectedAmbers.forEach { amber ->
            if (amber != null) { // 所有心法盘都可能包含暴击技能
                val levelBonusEach = if (diskLevel > 1) amber.amplification * (diskLevel - 1) else 0
                
                // 遍历心法盘的所有技能
                amber.skill.forEach { skillId ->
                    val skill = skills.find { it.skillId == skillId }
                    if (skill != null) {
                        val baseBonus = calculateCritBonusFromSkill(skill.desc)
                        // 心法盘技能可能有等级加成，但暴击技能通常不受等级影响
                        totalBonus += baseBonus
                    }
                }
            }
        }
    }
    
    return totalBonus
}

/**
 * 计算厨师的总暴击加成，使用个人数据中的厨具和心法盘
 * @param chef 厨师数据
 * @param equip 厨具数据
 * @param skills 技能数据列表
 * @param gameData 游戏数据（用于获取心法盘信息）
 * @param personalData 个人数据（用于获取心法盘信息）
 * @return 总暴击加成百分比
 */
private fun calculateTotalCritRateBonusWithEquip(
    chef: com.example.show_auto.data.Chef,
    equip: com.example.show_auto.data.Equip?,
    skills: List<com.example.show_auto.data.Skill>,
    gameData: com.example.show_auto.data.GameData?,
    personalData: com.example.show_auto.data.PersonalData?
): Double {
    var totalBonus = 0.0
    
    // 1. 计算厨师技能加成
    // 获取基础技能描述
    val baseSkillDesc = if (chef.skill > 0) {
        skills.find { it.skillId == chef.skill }?.desc ?: ""
    } else {
        ""
    }
    
    // 获取修炼技能描述
    val ultimateSkillDesc = getChefSkillDescription(chef, skills)
    
    // 合并厨师技能描述
    val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
    
    // 计算各类暴击相关技能
    totalBonus += calculateCritBonusFromSkill(combinedSkillDesc)
    
    // 2. 计算厨具加成
    if (equip != null) {
        // 检查厨师是否有厨具技法效果翻倍技能
        val hasEquipSkillMultiplier = hasEquipSkillMultiplier(chef, skills)
        val multiplier = if (hasEquipSkillMultiplier) 2.0 else 1.0
        
        // 遍历厨具的所有技能
        for (skillId in equip.skill) {
            val skill = skills.find { it.skillId == skillId }
            if (skill != null) {
                totalBonus += calculateCritBonusFromSkill(skill.desc) * multiplier
            }
        }
    }
    
    // 3. 计算心法盘加成（使用个人数据）
    if (gameData != null && personalData != null) {
        val pChef = personalData.chefs[chef.chefId]
        val diskLevel = (pChef?.dlv ?: 1).coerceAtLeast(1)
        val amberIds = pChef?.ambers ?: emptyList()
        
        if (amberIds.isNotEmpty()) {
            amberIds.forEach { aid ->
                if (aid == 0) return@forEach
                val amber = gameData.ambers.find { it.amberId == aid.toString() }
                if (amber != null) { // 所有心法盘都可能包含暴击技能
                    val levelBonusEach = if (diskLevel > 1) amber.amplification * (diskLevel - 1) else 0
                    
                    // 遍历心法盘的所有技能
                    amber.skill.forEach { sid ->
                        val skillObj = skills.find { it.skillId == sid }
                        if (skillObj != null) {
                            val baseBonus = calculateCritBonusFromSkill(skillObj.desc)
                            // 心法盘技能可能有等级加成，但暴击技能通常不受等级影响
                            totalBonus += baseBonus
                        }
                    }
                }
            }
        }
    }
    
    return totalBonus
}

/**
 * 检查厨师是否有暴击技能（包括厨具技能）
 * @param chef 厨师数据
 * @param equip 厨具数据
 * @param skills 技能数据列表
 * @param defaultAllUltimate 是否默认全修炼
 * @return 是否有暴击技能
 */
private fun hasCritSkillWithEquip(
    chef: com.example.show_auto.data.Chef?,
    equip: com.example.show_auto.data.Equip?,
    skills: List<com.example.show_auto.data.Skill>,
    defaultAllUltimate: Boolean = false
): Boolean {
    if (chef == null) return false
    
    // 1. 检查厨师基础技能和修炼技能
    val baseSkillDesc = if (chef.skill > 0) {
        skills.find { it.skillId == chef.skill }?.desc ?: ""
    } else {
        ""
    }
    val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(chef, skills, defaultAllUltimate)
    val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
    
    // 2. 检查厨具技能
    val equipSkillDesc = if (equip != null) {
        equip.skill.joinToString(" ") { skillId ->
            skills.find { it.skillId == skillId }?.desc ?: ""
        }
    } else {
        ""
    }
    
    // 3. 合并所有技能描述
    val allSkillDesc = "$combinedSkillDesc $equipSkillDesc"
    
    // 4. 检查是否包含暴击相关技能模式
    val critPatterns = listOf(
        "稀有客人赠礼数量\\d+%概率提升\\d+%", // 稀有客人赠礼数量X%概率提升X%
        "每制作一种神级料理贵客赠礼翻倍概率\\+\\d+(?:\\.\\d+)?%", // 每制作一种神级料理贵客赠礼翻倍概率+*%
        "贵客赠礼数量\\d+%概率提升\\d+%" // 贵客赠礼数量*%概率提升*%
    )
    
    return critPatterns.any { pattern ->
        pattern.toRegex().find(allSkillDesc) != null
    }
}

/**
 * 从技能描述中计算暴击加成
 * @param skillDesc 技能描述
 * @return 暴击加成百分比
 */
private fun calculateCritBonusFromSkill(skillDesc: String): Double {
    var totalBonus = 0.0
    
    // 1. 每制作一种神级料理贵客赠礼翻倍概率 +*%
    // 每制作一种神级料理贵客赠礼翻倍概率+10% -> 10 * 3 = 30%
    val doubleGiftPattern = "每制作一种神级料理贵客赠礼翻倍概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
    val doubleGiftMatches = doubleGiftPattern.findAll(skillDesc)
    for (match in doubleGiftMatches) {
        val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
        totalBonus += value * 3 // 每个厨师最多制作3道菜
    }
    
    // 2. 稀有客人赠礼数量*%概率提升*%
    // 例：稀有客人赠礼数量15%概率提升100% -> 15
    val giftQuantityPattern = "稀有客人赠礼数量(\\d+(?:\\.\\d+)?)%概率提升(\\d+(?:\\.\\d+)?)%".toRegex()
    val giftQuantityMatches = giftQuantityPattern.findAll(skillDesc)
    for (match in giftQuantityMatches) {
        val firstValue = match.groupValues[1].toDoubleOrNull() ?: 0.0
        totalBonus += firstValue // 只取第一个值
    }
    
    // 3. 贵客赠礼数量*%概率提升*%且稀有江湖贴出现概率+*%
    // 例：贵客赠礼数量15%概率提升100%且稀有江湖贴出现概率+10% -> 15
    val guestGiftPattern = "贵客赠礼数量(\\d+(?:\\.\\d+)?)%概率提升(\\d+(?:\\.\\d+)?)%且稀有江湖贴出现概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
    val guestGiftMatches = guestGiftPattern.findAll(skillDesc)
    for (match in guestGiftMatches) {
        val firstValue = match.groupValues[1].toDoubleOrNull() ?: 0.0
        totalBonus += firstValue // 只取第一个值
    }
    
    return totalBonus
}

/**
 * 计算百锅产出
 * @param actualGuestRate 实际贵客率
 * @param runeRate 符文率
 * @param critRate 暴击率
 * @return 百锅产出，保留2位小数
 */
private fun calculateHundredPotOutput(
    actualGuestRate: Double,
    runeRate: Int,
    critRate: Double
): Double {
    // 实际贵客率为0时不进行计算
    if (actualGuestRate <= 0.0) {
        return 0.0
    }
    
    // 按照jisuan文件的逻辑：0.01 * 实际贵客率 * 符文率 * 暴击率，截断取整后除以100
    val result = 0.01 * actualGuestRate * runeRate * critRate
    return truncate(result) / 100.0
}

/**
 * 计算单位食材
 * @param actualGuestRate 实际贵客率
 * @param runeRate 符文率
 * @param critRate 暴击率
 * @param quantity 份数
 * @return 单位食材，保留2位小数
 */
private fun calculateUnitFood(
    actualGuestRate: Double,
    runeRate: Int,
    critRate: Double,
    quantity: Int
): Double {
    // 实际贵客率为0或份数为0时不进行计算
    if (actualGuestRate <= 0.0 || quantity <= 0) {
        return 0.0
    }
    
    // 按照jisuan文件的逻辑：0.1 / 份数 * 实际贵客率 * 符文率 * 暴击率，截断取整后除以100
    val result = 0.1 / quantity * actualGuestRate * runeRate * critRate
    return truncate(result) / 100.0
}

/**
 * 计算单位时间
 * @param unitFood 单位食材
 * @param timeRate 时间效率
 * @return 单位时间，保留2位小数
 */
private fun calculateUnitTime(
    unitFood: Double,
    timeRate: Double
): Double {
    // 单位食材为0或时间效率为0时不进行计算
    if (unitFood <= 0.0 || timeRate <= 0.0) {
        return 0.0
    }
    
    // 按照jisuan文件的逻辑：单位食材 * 100 / 时间效率 * 100，截断取整后除以100
    val result = unitFood * 100 / timeRate * 100
    return truncate(result) / 100.0
}

/**
 * 菜谱分配结果数据类
 */
data class RecipeAllocationResult(
    val chefGroup: List<com.example.show_auto.data.Chef>,
    val allocatedRecipes: List<AllocatedRecipe>,
    val totalCookingTime: Int, // 总制作时间（秒）
    val totalGuestRate: Double,
    val totalCritRate: Double,
    val totalTimeBonus: Double,
    val unitTime: Double,
    val hundredPotOutput: Double,
    val unitFood: Double,
    val enhancedChefs: List<com.example.show_auto.data.Chef> = emptyList() // 每个厨师的最终技法值（包含所有加成）
)

/**
 * 已分配的菜谱数据类
 */
data class AllocatedRecipe(
    val recipe: com.example.show_auto.data.Recipe,
    val assignedChef: com.example.show_auto.data.Chef,
    val rune: String,
    val quantity: Int, // 分配份数
    val cookingTime: Int, // 制作时间（秒）
    val quality: String, // 制作品级
    val isSupplemented: Boolean = false // 是否为强补菜谱
)

/**
 * 一键查询结果数据类
 */
data class OneClickQueryResult(
    val chefGroup: List<com.example.show_auto.data.Chef>,
    val totalGuestRate: Double,
    val totalCritRate: Double,
    val totalTimeBonus: Double,
    val unitTime: Double,
    val hundredPotOutput: Double,
    val unitFood: Double,
    val recommendedRank: String, // 推荐的品级（自动检测或默认）
    val enhancedChefs: List<com.example.show_auto.data.Chef> = emptyList() // 每个厨师的最终技法值（包含所有加成）
)

/**
 * 计算同贵客双菜谱的数据
 * @param baseGuestRate 场上贵客率
 * @param starLevel1 菜谱1星级
 * @param quantity1 菜谱1份数
 * @param starLevel2 菜谱2星级
 * @param quantity2 菜谱2份数
 * @return 包含各种计算结果的数据类
 */
data class DualRecipeResult(
    val actualGuestRate1: Double,
    val actualGuestRate2: Double,
    val totalGuestRate: Double,
    val runeAProbability: Double,
    val runeBProbability: Double,
    val scatterProbability: Double
)

private fun calculateDualRecipeData(
    baseGuestRate: Double,
    starLevel1: Int,
    quantity1: Int,
    starLevel2: Int,
    quantity2: Int
): DualRecipeResult {
    // 内部计算实际贵客率的函数
    fun calculateActualGuestRateInternal(starLevel: Int, quantity: Int, baseGuestRate: Double): Double {
        // 按照jisuan文件的逻辑计算实际贵客率
        val actualGuestRate = when (starLevel) {
            1 -> {
                if (quantity < 20) {
                    0.0
                } else {
                    (0.05 + (quantity - 20) * 0.013) * (100 + baseGuestRate)
                }
            }
            2 -> {
                if (quantity < 15) {
                    0.0
                } else {
                    (0.08 + (quantity - 15) * 0.02) * (100 + baseGuestRate)
                }
            }
            3 -> {
                if (quantity < 12) {
                    0.0
                } else {
                    (0.083 + (quantity - 12) * 0.016) * (100 + baseGuestRate)
                }
            }
            4 -> {
                if (quantity < 10) {
                    0.0
                } else {
                    (0.1142 + (quantity - 10) * 0.0059) * (100 + baseGuestRate)
                }
            }
            5 -> {
                if (quantity < 7) {
                    0.0
                } else {
                    (0.1006 + (quantity - 7) * 0.0084) * (100 + baseGuestRate)
                }
            }
            else -> 0.0
        }
        
        // 按照jisuan文件的逻辑：截断取整后除以100
        return truncate(actualGuestRate * 100.0) / 100.0
    }
    
    // 计算实际贵客率1
    val actualGuestRate1 = calculateActualGuestRateInternal(starLevel1, quantity1, baseGuestRate)
    
    // 计算实际贵客率2
    val actualGuestRate2 = calculateActualGuestRateInternal(starLevel2, quantity2, baseGuestRate)
    
    // 计算总贵客率
    val totalGuestRate = actualGuestRate1 + actualGuestRate2
    
    // 按照jisuan文件逻辑：计算符文概率时使用限制后的总贵客率（最大100）
    val limitedTotalGuestRate = if (totalGuestRate > 100.0) 100.0 else totalGuestRate
    
    // 计算撒币概率：限制后的总贵客率 / 2，截断取整后除以100
    val scatterProbability = truncate(limitedTotalGuestRate / 2.0 * 100.0) / 100.0
    
    // 计算符文A概率和符文B概率（使用限制后的总贵客率）
    val runeAProbability: Double
    val runeBProbability: Double
    
    if ((actualGuestRate1 + actualGuestRate2).compareTo(0.0) > 0) {
        // 符文A概率：实际贵客率1 / (实际贵客率1 + 实际贵客率2) * 限制后总贵客率 / 2
        val runeARaw = actualGuestRate1 / (actualGuestRate1 + actualGuestRate2) * limitedTotalGuestRate / 2.0
        runeAProbability = truncate(runeARaw * 100.0) / 100.0
        
        // 符文B概率：实际贵客率2 / (实际贵客率1 + 实际贵客率2) * 限制后总贵客率 / 2
        val runeBRaw = actualGuestRate2 / (actualGuestRate1 + actualGuestRate2) * limitedTotalGuestRate / 2.0
        runeBProbability = truncate(runeBRaw * 100.0) / 100.0
    } else {
        runeAProbability = 0.0
        runeBProbability = 0.0
    }
    
    return DualRecipeResult(
        actualGuestRate1 = actualGuestRate1,
        actualGuestRate2 = actualGuestRate2,
        totalGuestRate = totalGuestRate, // 返回原始值，在UI中处理显示限制
        runeAProbability = if (runeAProbability < 0) 0.0 else runeAProbability,
        runeBProbability = if (runeBProbability < 0) 0.0 else runeBProbability,
        scatterProbability = scatterProbability
    )
}

/**
 * 生成厨师组合（3个厨师一组）
 * @param chefs 厨师列表
 * @return 所有可能的3厨师组合列表
 */
private fun generateChefCombinations(chefs: List<com.example.show_auto.data.Chef>): List<List<com.example.show_auto.data.Chef>> {
    System.out.println("开始生成厨师组合，总厨师数: ${chefs.size}")
    
    val combinations = mutableListOf<List<com.example.show_auto.data.Chef>>()
    val n = chefs.size
    
    // 如果厨师数量少于3个，无法组成组合
    if (n < 3) {
        System.out.println("厨师数量不足3个，无法生成组合")
        return combinations
    }
    
    // 生成所有可能的3厨师组合（C(n,3) = n!/(3!(n-3)!)）
    for (i in 0 until n - 2) {
        for (j in i + 1 until n - 1) {
            for (k in j + 1 until n) {
                val combination = listOf(chefs[i], chefs[j], chefs[k])
                combinations.add(combination)
            }
        }
    }
    
    System.out.println("生成组合完成，总组合数: ${combinations.size}")
    
    return combinations
}

/**
 * 批量计算所有厨师组合的结果
 * @param chefGroups 厨师组合列表
 * @param skills 技能数据
 * @param gameData 游戏数据
 * @param personalData 个人数据
 * @param settingsStorage 设置存储
 * @return 计算结果列表
 */
private fun calculateAllChefGroups(
    chefGroups: List<List<com.example.show_auto.data.Chef>>,
    skills: List<com.example.show_auto.data.Skill>,
    gameData: com.example.show_auto.data.GameData,
    personalData: com.example.show_auto.data.PersonalData?,
    settingsStorage: com.example.show_auto.data.SettingsStorage,
    ultimateSkills: UltimateSkillsState
): List<OneClickQueryResult> {
    
    val results = mutableListOf<OneClickQueryResult>()
    
    chefGroups.forEachIndexed { groupIndex, chefGroup ->
        
        try {
            val result = calculateSingleChefGroup(
                chefGroup = chefGroup,
                skills = skills,
                gameData = gameData,
                personalData = personalData,
                settingsStorage = settingsStorage,
                ultimateSkills = ultimateSkills
            )
            
            if (result != null) {
                results.add(result)
            } else {
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    
    return results
}

/**
 * 计算单个厨师组合的结果
 * @param chefGroup 厨师组合（3个厨师）
 * @param skills 技能数据
 * @param gameData 游戏数据
 * @param personalData 个人数据
 * @param settingsStorage 设置存储
 * @return 计算结果，如果计算失败返回null
 */
private fun calculateSingleChefGroup(
    chefGroup: List<com.example.show_auto.data.Chef>,
    skills: List<com.example.show_auto.data.Skill>,
    gameData: com.example.show_auto.data.GameData,
    personalData: com.example.show_auto.data.PersonalData?,
    settingsStorage: com.example.show_auto.data.SettingsStorage,
    ultimateSkills: UltimateSkillsState
): OneClickQueryResult? {
    if (chefGroup.size != 3) {
        System.out.println("厨师组合数量不正确: ${chefGroup.size}")
        return null
    }
    
    try {
        // 1. 计算总贵客率（3个厨师的贵客率之和）
        var totalGuestRate = 0.0
        var totalCritRate = 0.0
        var totalTimeBonus = 0.0
        
        val enhancedChefs = mutableListOf<com.example.show_auto.data.Chef>()
        
        chefGroup.forEachIndexed { chefIndex, chef ->
            // 根据"启用厨具遗玉"设置决定是否获取厨具数据
            val chefEquip = if (settingsStorage.getCalculatorUsePersonalData() && personalData != null && gameData != null) {
                val equipId = personalData.chefs[chef.chefId]?.equip
                if (equipId != null) {
                    gameData.equips.find { it.equipId == equipId.toString() }
                } else {
                    null
                }
            } else {
                null
            }
            
            // 根据"启用厨具遗玉"设置决定是否使用个人数据计算加成
            val guestRateBonus = if (settingsStorage.getCalculatorUsePersonalData()) {
                calculateTotalGuestRateBonusWithMaxAmber(chef, skills, gameData, personalData, settingsStorage.getCalculatorDefaultMaxLevelAmber(), settingsStorage.getCalculatorDefaultAllUltimate())
            } else {
                // 当"启用厨具遗玉"关闭时，不使用个人数据中的厨具和心法盘，但使用心法盘默认满级设置
                val useMaxLevelAmber = settingsStorage.getCalculatorDefaultMaxLevelAmber()
                calculateTotalGuestRateBonusWithMaxAmber(chef, skills, gameData, null, useMaxLevelAmber, settingsStorage.getCalculatorDefaultAllUltimate())
            }
            
            // 根据"启用厨具遗玉"设置决定是否使用个人数据计算暴击率
            val critRateBonus = if (settingsStorage.getCalculatorUsePersonalData()) {
                calculateTotalCritRateForCalculator(chef, skills, gameData, personalData, settingsStorage.getCalculatorDefaultAllUltimate()) - 100.0
            } else {
                // 当"启用厨具遗玉"关闭时，不使用个人数据中的厨具和心法盘，但使用心法盘默认满级设置
                // 注意：暴击率计算函数不直接支持心法盘默认满级，但会通过贵客率计算间接影响
                calculateTotalCritRateForCalculator(chef, skills, gameData, null, settingsStorage.getCalculatorDefaultAllUltimate()) - 100.0
            }
            
            // 根据"启用厨具遗玉"设置决定是否使用个人数据计算时间加成
            val timeBonus = if (settingsStorage.getCalculatorUsePersonalData()) {
                calculateOpeningTimeBonus(chef, chefEquip, skills, gameData, personalData, settingsStorage.getCalculatorDefaultAllUltimate())
            } else {
                // 当"启用厨具遗玉"关闭时，不使用个人数据中的厨具和心法盘，但使用心法盘默认满级设置
                // 注意：时间加成计算函数不直接支持心法盘默认满级，但会通过贵客率计算间接影响
                calculateOpeningTimeBonus(chef, null, skills, gameData, null, settingsStorage.getCalculatorDefaultAllUltimate())
            }
            
            // 计算最终技法值 - 完全复刻厨师选择对话框中的逻辑
            // 使用传入的真实个人技法数据
            
            // 计算厨师间技法影响（模拟厨师选择对话框中的逻辑）
            val chefInteractions = com.example.show_auto.utils.ChefInteractionCalculator.calculateChefInteractions(
                chefGroup, skills, settingsStorage.getSelectedAuraChefs()
            )
            val chefInteractionBonus = chefInteractions.getOrNull(chefIndex)
            
            // 根据"启用厨具遗玉"设置决定是否使用厨具进行技法加成计算
            val enhancedChef = if (settingsStorage.getCalculatorUsePersonalData()) {
                // 当"启用厨具遗玉"开启时，使用厨具进行技法加成计算
                com.example.show_auto.utils.ChefSkillCalculator.applyAllSkills(
                    chef, ultimateSkills, chefEquip, skills, chefInteractionBonus
                )
            } else {
                // 当"启用厨具遗玉"关闭时，不使用厨具，只基于厨师本身的技能进行技法加成计算
                com.example.show_auto.utils.ChefSkillCalculator.applyAllSkills(
                    chef, ultimateSkills, null, skills, chefInteractionBonus
                )
            }
            
            // 计算受心法盘影响的技法值（模拟厨师选择对话框中的逻辑）
            val techniqueValuesWithAmbers = if (settingsStorage.getCalculatorUsePersonalData() && personalData != null && gameData != null) {
                // 当启用厨具遗玉时，使用厨师个人数据中的心法盘配置
                val personalChef = personalData.chefs[chef.chefId]
                val chefAmbers = if (personalChef?.ambers != null && personalChef.ambers.isNotEmpty()) {
                    val ambers = mutableListOf<com.example.show_auto.data.Amber?>()
                    personalChef.ambers.forEach { amberId ->
                        val amber = gameData.ambers.find { it.amberId == amberId.toString() }
                        ambers.add(amber)
                    }
                    // 确保有3个位置
                    while (ambers.size < 3) {
                        ambers.add(null)
                    }
                    ambers.take(3)
                } else {
                    listOf(null, null, null)
                }
                
                // 获取厨师等级（使用个人数据中的等级）
                val chefLevel = personalChef?.dlv ?: 1
                
                // 如果开启了心法盘默认满级，则对所有蓝色心法盘位置使用满朋陨
                val finalAmbers = if (settingsStorage.getCalculatorDefaultMaxLevelAmber()) {
                    applyMaxLevelAmberToBluePositions(chef, chefAmbers.toMutableList(), gameData, true)
                } else {
                    chefAmbers
                }
                
                System.out.println("厨师 ${chef.name} 使用个人数据中的心法盘配置，等级: $chefLevel")
                
                // 计算心法盘技法值加成
                calculateTechniqueValuesWithAmbers(chef, skills, gameData, chefLevel, finalAmbers, enhancedChef)
            } else {
                emptyMap()
            }
            
            // 构建最终技法值字符串（包含心法盘加成，模拟厨师选择对话框中的显示格式）
            val skillValues = mutableListOf<String>()
            
            // 炒技法
            val finalStirfry = techniqueValuesWithAmbers["stirfry"]?.second ?: enhancedChef.stirfry
            if (finalStirfry > 0) skillValues.add("炒:${finalStirfry}")
            
            // 煮技法
            val finalBoil = techniqueValuesWithAmbers["boil"]?.second ?: enhancedChef.boil
            if (finalBoil > 0) skillValues.add("煮:${finalBoil}")
            
            // 切技法
            val finalKnife = techniqueValuesWithAmbers["knife"]?.second ?: enhancedChef.knife
            if (finalKnife > 0) skillValues.add("刀:${finalKnife}")
            
            // 炸技法
            val finalFry = techniqueValuesWithAmbers["fry"]?.second ?: enhancedChef.fry
            if (finalFry > 0) skillValues.add("炸:${finalFry}")
            
            // 烤技法
            val finalBake = techniqueValuesWithAmbers["bake"]?.second ?: enhancedChef.bake
            if (finalBake > 0) skillValues.add("烤:${finalBake}")
            
            // 蒸技法
            val finalSteam = techniqueValuesWithAmbers["steam"]?.second ?: enhancedChef.steam
            if (finalSteam > 0) skillValues.add("蒸:${finalSteam}")
            
            val finalSkillText = if (skillValues.isNotEmpty()) skillValues.joinToString(",") else "无技法值"
            
            // 添加调试日志：输出心法盘技法值加成信息
            if (techniqueValuesWithAmbers.isNotEmpty()) {
                System.out.println("厨师 ${chef.name} 心法盘技法值加成计算:")
                techniqueValuesWithAmbers.forEach { (techniqueType, values) ->
                    val (baseValue, finalValue) = values
                    if (baseValue != finalValue) {
                        val techniqueName = when (techniqueType) {
                            "stirfry" -> "炒"
                            "boil" -> "煮"
                            "knife" -> "切"
                            "fry" -> "炸"
                            "bake" -> "烤"
                            "steam" -> "蒸"
                            else -> techniqueType
                        }
                        System.out.println("  ${techniqueName}技法: $baseValue -> $finalValue (+${finalValue - baseValue})")
                    }
                }
            }
            
            // 添加调试日志
            
            totalGuestRate += guestRateBonus
            totalCritRate += critRateBonus
            totalTimeBonus += timeBonus
            
            // 创建包含心法盘加成的最终厨师数据
            val finalEnhancedChef = if (techniqueValuesWithAmbers.isNotEmpty()) {
                enhancedChef.copy(
                    stirfry = techniqueValuesWithAmbers["stirfry"]?.second ?: enhancedChef.stirfry,
                    boil = techniqueValuesWithAmbers["boil"]?.second ?: enhancedChef.boil,
                    knife = techniqueValuesWithAmbers["knife"]?.second ?: enhancedChef.knife,
                    fry = techniqueValuesWithAmbers["fry"]?.second ?: enhancedChef.fry,
                    bake = techniqueValuesWithAmbers["bake"]?.second ?: enhancedChef.bake,
                    steam = techniqueValuesWithAmbers["steam"]?.second ?: enhancedChef.steam
                )
            } else {
                enhancedChef
            }
            
            enhancedChefs.add(finalEnhancedChef)
        }
        
        // 添加总和的调试日志
        
        // 2. 检测是否有特殊技能，决定品级和符文率
        val starLevel = 5 // 默认5星
        val quantity = 7 // 默认7份
        
        // 检测厨师组合中是否有"场上厨师制作特级及以上料理时此料理贵客符文概率+*%"类技能
        var hasSpecialRuneSkill = false
        var recommendedRank = "可" // 默认品级
        
        for (chef in chefGroup) {
            // 获取厨师的基础技能描述
            val baseSkillDesc = if (chef.skill > 0) {
                skills.find { it.skillId == chef.skill }?.desc ?: ""
            } else {
                ""
            }
            
            // 获取厨师的修炼技能描述（使用override版本，确保未拥有厨师也能正确计算修炼技能）
            val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(chef, skills, settingsStorage.getCalculatorDefaultAllUltimate())
            val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
            
            // 检查是否包含"场上厨师制作特级及以上料理时此料理贵客符文概率+*%"类技能
            val specialSkillPattern = "场上厨师制作特级及以上料理时此料理贵客符文概率\\+(\\d+(?:\\.\\d+)?)%"
            val matchResult = specialSkillPattern.toRegex().find(combinedSkillDesc)
            
            if (matchResult != null) {
                hasSpecialRuneSkill = true
                System.out.println("检测到厨师 ${chef.name} 有特殊符文技能: ${matchResult.value}")
                break // 找到一个就够了
            }
        }
        
        // 如果有特殊技能，自动设置为特级品级
        if (hasSpecialRuneSkill) {
            recommendedRank = "特"
            System.out.println("检测到特殊符文技能，自动将品级设置为特级")
        }
        
        // 根据品级计算符文率（使用与计算结果card相同的逻辑，传入defaultAllUltimate参数）
        val runeRate = getRuneRateByRankWithOverride(recommendedRank, chefGroup, skills, settingsStorage.getCalculatorDefaultAllUltimate())
        
        // 3. 计算实际贵客率
        val actualGuestRate = when (starLevel) {
            1 -> if (quantity < 20) 0.0 else (0.05 + (quantity - 20) * 0.013) * (100 + totalGuestRate)
            2 -> if (quantity < 15) 0.0 else (0.08 + (quantity - 15) * 0.02) * (100 + totalGuestRate)
            3 -> if (quantity < 12) 0.0 else (0.083 + (quantity - 12) * 0.016) * (100 + totalGuestRate)
            4 -> if (quantity < 10) 0.0 else (0.1142 + (quantity - 10) * 0.0059) * (100 + totalGuestRate)
            5 -> if (quantity < 7) 0.0 else (0.1006 + (quantity - 7) * 0.0084) * (100 + totalGuestRate)
            else -> if (quantity < 7) 0.0 else (0.1006 + (quantity - 7) * 0.0084) * (100 + totalGuestRate)
        }.let { truncate(it * 100.0) / 100.0 }
        
        // 4. 计算百锅产出
        // 注意：应该使用实际的暴击率（100 + 加成），而不是加成值
        val actualCritRate = 100.0 + totalCritRate
        val hundredPotOutput = if (actualGuestRate <= 0.0) 0.0 else {
            val result = 0.01 * actualGuestRate * runeRate.toDouble() * actualCritRate
            truncate(result) / 100.0
        }
        
        // 5. 计算单位食材
        // 注意：应该使用实际的暴击率（100 + 加成），而不是加成值
        val unitFood = if (actualGuestRate <= 0.0 || quantity <= 0) 0.0 else {
            val result = 0.1 / quantity * actualGuestRate * runeRate.toDouble() * actualCritRate
            truncate(result) / 100.0
        }
        
        // 6. 计算单位时间
        // 注意：totalTimeBonus可以为负数（表示时间变快），所以不应该用 <= 0.0 作为判断条件
        // 应该检查最终时间是否大于0
        val finalTimeRate = 100.0 + totalTimeBonus
        
        // 添加调试日志
        
        // 单位时间计算公式：单位食材 / 时间百分比
        // 例如：单位食材=10.90，时间=80%，则单位时间=10.90/80%=13.625
        val unitTime = if (unitFood <= 0.0 || finalTimeRate <= 0.0) {
            0.0
        } else {
            val result = unitFood / (finalTimeRate / 100.0)
            val truncatedResult = truncate(result * 100.0) / 100.0
            System.out.println("  调试信息 - 单位时间计算: ${unitFood} / (${finalTimeRate} / 100) = ${unitFood} / ${finalTimeRate / 100.0} = ${result}, 截断后: ${truncatedResult}")
            truncatedResult
        }
        
        return OneClickQueryResult(
            chefGroup = chefGroup,
            totalGuestRate = totalGuestRate,
            // 存储实际值，而不是加成值
            totalCritRate = 100.0 + totalCritRate,
            totalTimeBonus = 100.0 + totalTimeBonus,
            unitTime = unitTime,
            hundredPotOutput = hundredPotOutput,
            unitFood = unitFood,
            recommendedRank = recommendedRank,
            enhancedChefs = enhancedChefs
        )
        
    } catch (e: Exception) {
        System.out.println("计算厨师组合时发生异常: ${e.message}")
        e.printStackTrace()
        return null
    }
}

/**
 * 根据多个符文查询无冲突菜谱（调用查询贵客冲突页面的冲突检测逻辑）
 * @param runeNames 符文名称列表
 * @param gameData 游戏数据
 * @param skills 技能数据
 * @return 无冲突的符文菜谱列表
 */
private fun queryRuneRecipesByMultipleRunes(
    runeNames: List<String>,
    gameData: com.example.show_auto.data.GameData,
    skills: List<com.example.show_auto.data.Skill>
): List<com.example.show_auto.data.Recipe> {
    System.out.println("queryRuneRecipesByMultipleRunes 函数被调用")
    System.out.println("查询符文: ${runeNames.joinToString(", ")}")
    
    try {
        // 第一步：收集所有相关的菜谱和其对应的符文（跨符文）
        val recipeToRunesMap = mutableMapOf<String, MutableSet<String>>()
        
        runeNames.forEach { runeName ->
            gameData.guests.forEach { guest ->
                guest.gifts.forEach { gift ->
                    if (gift.antique == runeName) {
                        val recipe = gameData.recipes.find { it.name == gift.recipe && it.got }
                        if (recipe != null) {
                            recipeToRunesMap.getOrPut(recipe.name) { mutableSetOf() }.add(runeName)
                        }
                    }
                }
            }
        }
        
        // 第二步：全局按贵客分组（跨符文冲突检测）
        val recipesByGuest = mutableMapOf<String, MutableList<com.example.show_auto.data.Recipe>>()
        
        recipeToRunesMap.keys.forEach { recipeName ->
            val recipe = gameData.recipes.find { it.name == recipeName && it.got }
            if (recipe != null) {
                gameData.guests.forEach { guest ->
                    val hasRecipeForSelectedRunes = runeNames.any { runeName ->
                        guest.gifts.any { gift -> gift.recipe == recipe.name && gift.antique == runeName }
                    }
                    if (hasRecipeForSelectedRunes) {
                        val guestRecipes = recipesByGuest.getOrPut(guest.name) { mutableListOf() }
                        if (!guestRecipes.any { it.name == recipe.name }) {
                            guestRecipes.add(recipe)
                        }
                    }
                }
            }
        }
        
        // 第三步：全局冲突检测（跨符文）
        val allNoConflict = mutableListOf<com.example.show_auto.data.Recipe>()
        
        recipesByGuest.forEach { (_, recipes) ->
            if (recipes.size == 1) {
                // 只有一个菜谱，无冲突
                allNoConflict.addAll(recipes)
            } else {
                // 多个菜谱有冲突，需要选择一个作为无冲突
                // 双贵客菜谱时间除以2后再判断
                // 先收集所有菜谱的贵客数量信息
                val recipeGuestCountMap = mutableMapOf<String, Int>()
                recipes.forEach { recipe ->
                    val guestCount = gameData.guests.count { guest ->
                        guest.gifts.any { gift -> 
                            gift.recipe == recipe.name 
                        }
                    }
                    recipeGuestCountMap[recipe.name] = guestCount
                }
                
                val recipesWithAdjustedTime = recipes.map { recipe ->
                    val guestCount = recipeGuestCountMap[recipe.name] ?: 1
                    val adjustedTime = if (guestCount >= 2) {
                        recipe.time / 2.0
                    } else {
                        recipe.time.toDouble()
                    }
                    Triple(recipe, adjustedTime, guestCount)
                }
                
                // 按调整后的时间排序
                val sortedByAdjustedTime = recipesWithAdjustedTime.sortedBy { it.second }
                
                // 选择调整后时间最短的作为无冲突菜谱
                val selectedRecipeInfo = sortedByAdjustedTime.first()
                val selectedRecipe = selectedRecipeInfo.first
                val selectedAdjustedTime = selectedRecipeInfo.second
                val selectedGuestCount = selectedRecipeInfo.third
                
                allNoConflict.add(selectedRecipe)
                
                // 输出调试信息
                val timeInfo = if (selectedGuestCount >= 2) {
                    "多贵客菜谱(时间${selectedRecipe.time}秒/2=${selectedAdjustedTime.toInt()}秒)"
                } else {
                    "单贵客菜谱(时间${selectedRecipe.time}秒)"
                }
                System.out.println("一键查询冲突检测: 选择 ${selectedRecipe.name} 作为无冲突菜谱 ($timeInfo)")
            }
        }
        
        // 第四步：按符文重新分组，只返回无冲突的菜谱
        val noConflictRecipes = mutableListOf<com.example.show_auto.data.Recipe>()
        val sortComparator = compareByDescending<com.example.show_auto.data.Recipe> { it.got }.thenBy { it.time }
        
        runeNames.forEach { runeName ->
            val runeNoConflict = allNoConflict.filter { recipe ->
                recipeToRunesMap[recipe.name]?.contains(runeName) == true
            }.distinctBy { it.name }  // 按菜谱名称去重
            
            noConflictRecipes.addAll(runeNoConflict)
        }
        
        // 去重并排序
        val finalRecipes = noConflictRecipes.distinctBy { it.name }.sortedWith(sortComparator)
        
        System.out.println("查询到 ${finalRecipes.size} 个无冲突的已拥有符文菜谱")
        return finalRecipes
        
    } catch (e: Exception) {
        System.out.println("查询符文菜谱时发生错误: ${e.message}")
        e.printStackTrace()
        return emptyList()
    }
}

/**
 * 执行一键查询逻辑
 * @param gameData 游戏数据
 * @param skills 技能数据
 * @param personalData 个人数据
 * @param settingsStorage 设置存储
 * @param defaultMaxLevelAmber 是否使用默认满级心法盘
 * @param onResultUpdate 结果更新回调
 * @param onProgressUpdate 进度更新回调
 * @param onSelectionUpdate 选择框更新回调
 */
private fun performOneClickQuery(
    gameData: com.example.show_auto.data.GameData?,
    skills: List<com.example.show_auto.data.Skill>,
    personalData: com.example.show_auto.data.PersonalData?,
    settingsStorage: com.example.show_auto.data.SettingsStorage,
    defaultMaxLevelAmber: Boolean,
    ultimateSkills: UltimateSkillsState,
    useAllChefs: Boolean, // 新增：使用全部厨师设置
    onResultUpdate: (OneClickQueryResult?) -> Unit,
    onProgressUpdate: (Boolean) -> Unit,
    onSelectionUpdate: (List<com.example.show_auto.data.Chef>, List<com.example.show_auto.data.Equip>, List<List<com.example.show_auto.data.Amber?>>, List<Int>, String) -> Unit,
    onRecipeUpdate: (Map<Int, List<com.example.show_auto.data.Recipe>>, Double) -> Unit, // 新增：菜谱更新回调，按厨师槽位分组，包含总贵客率
    existingChefs: List<com.example.show_auto.data.Chef> = emptyList(), // 新增：当前场上已选择的厨师列表
    calculatorLevels: List<Int?> = emptyList(), // 新增：厨师选择框中的等级配置
    calculatorAmbers: List<List<com.example.show_auto.data.Amber?>> = emptyList(), // 新增：厨师选择框中的心法盘配置
    calculatorEquips: List<com.example.show_auto.data.Equip> = emptyList(), // 新增：厨师选择框中的厨具配置
    recipeLimits: com.example.show_auto.ui.pages.RecipeLimitsState // 新增：个人菜谱上限设置
) {
    System.out.println("performOneClickQuery 函数被调用")
    
    // 设置计算进度状态
    onProgressUpdate(true)
    
    if (gameData == null) {
        System.out.println("游戏数据为空，无法执行一键查询")
        onProgressUpdate(false)
        return
    }
    
    // 声明 results 变量，确保在 if-else 分支外可以访问
    var results: List<OneClickQueryResult> = emptyList()
    
    // 检查场上是否已存在厨师
    if (existingChefs.isNotEmpty()) {
        System.out.println("场上已存在厨师，跳过厨师查询和计算步骤，直接进行菜谱分配")
        System.out.println("已存在厨师数量: ${existingChefs.size}")
        existingChefs.forEachIndexed { index, chef ->
            System.out.println("  厨师${index + 1}: ID=${chef.chefId}, 名称=${chef.name}, 星级=${chef.rarity}")
        }
        
        // 直接跳转到第二阶段：符文菜谱查询和菜谱分配
        System.out.println("=== 跳过第一阶段，直接执行第二阶段：符文菜谱查询和菜谱分配 ===")
        
        // 将现有厨师作为最优组合，直接进行菜谱分配
        val existingChefGroup = existingChefs
        
        // 动态计算厨师选择框中的实际值
        var totalGuestRate = 0.0
        var totalCritRate = 0.0
        var totalTimeBonus = 0.0
        
        // 遍历厨师，使用与厨师选择框相同的计算方式
        existingChefGroup.forEachIndexed { index, chef ->
            // 获取厨师选择框中实际选择的配置
            val level = if (index < calculatorLevels.size) calculatorLevels[index] else 1
            val ambers = if (index < calculatorAmbers.size) calculatorAmbers[index] else listOf(null, null, null)
            val equip = if (index < calculatorEquips.size) calculatorEquips[index] else null
            
            // 计算贵客率
            val guestRate = calculateTotalGuestRateBonusWithCalculatorData(
                chef, 
                skills, 
                gameData, 
                personalData, 
                level, 
                ambers, 
                equip, 
                settingsStorage.getCalculatorDefaultAllUltimate()
            )
            
            // 计算暴击率
            val critRate = if (equip != null && equip.name.isNotEmpty()) {
                var totalCritRate = 0.0
                
                // 1. 计算基础技能暴击率
                if (chef.skill > 0) {
                    val baseSkill = skills.find { it.skillId == chef.skill }
                    if (baseSkill != null) {
                        totalCritRate += extractCritRateFromSkillForCalculator(baseSkill.desc)
                    }
                }
                
                // 2. 计算修炼技能暴击率
                val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(chef, skills, settingsStorage.getCalculatorDefaultAllUltimate())
                totalCritRate += extractCritRateFromSkillForCalculator(ultimateSkillDesc)
                
                // 3. 计算厨具暴击率
                if (equip.skill.isNotEmpty()) {
                    for (skillId in equip.skill) {
                        val skill = skills.find { it.skillId == skillId }
                        if (skill != null) {
                            totalCritRate += extractCritRateFromSkillForCalculator(skill.desc)
                        }
                    }
                }
                
                totalCritRate
            } else {
                var totalCritRate = 0.0
                
                // 1. 计算基础技能暴击率
                if (chef.skill > 0) {
                    val baseSkill = skills.find { it.skillId == chef.skill }
                    if (baseSkill != null) {
                        totalCritRate += extractCritRateFromSkillForCalculator(baseSkill.desc)
                    }
                }
                
                // 2. 计算修炼技能暴击率
                val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(chef, skills, settingsStorage.getCalculatorDefaultAllUltimate())
                totalCritRate += extractCritRateFromSkillForCalculator(ultimateSkillDesc)
                
                totalCritRate
            }
            
            // 计算时间加成
            val timeBonus = calculateOpeningTimeBonus(chef, equip, skills, gameData, personalData, settingsStorage.getCalculatorDefaultAllUltimate())
            
            totalGuestRate += guestRate
            totalCritRate += critRate
            totalTimeBonus += timeBonus
            
            System.out.println("厨师 ${chef.name} (ID:${chef.chefId}, 星级:${chef.rarity}) - 贵客率:${String.format("%.2f", guestRate)}%, 暴击率:${String.format("%.2f", critRate)}%, 时间:${String.format("%.2f", timeBonus)}%")
        }
        
        // 计算最终的总值
        val finalCritRate = 100.0 + totalCritRate
        val finalTimeRate = 100.0 + totalTimeBonus
        
        System.out.println("动态计算厨师选择框中的值 - 总贵客率:${String.format("%.2f", totalGuestRate)}%, 总暴击率:${String.format("%.2f", finalCritRate)}%, 时间:${String.format("%.2f", finalTimeRate)}%")
        
        // 当场上有厨师时，需要创建包含正确技法值的enhancedChefs
        // 使用与厨师选择框相同的计算方式获取技法值
        val enhancedChefsWithSkills = mutableListOf<com.example.show_auto.data.Chef>()
        
        existingChefGroup.forEachIndexed { index, chef ->
            // 获取厨师选择框中实际选择的配置
            val level = if (index < calculatorLevels.size) calculatorLevels[index] else 1
            val ambers = if (index < calculatorAmbers.size) calculatorAmbers[index] else listOf(null, null, null)
            val equip = if (index < calculatorEquips.size) calculatorEquips[index] else null
            
            // 计算厨师间技法影响
            val chefInteractions = com.example.show_auto.utils.ChefInteractionCalculator.calculateChefInteractions(
                existingChefGroup, skills, settingsStorage.getSelectedAuraChefs()
            )
            val chefInteractionBonus = chefInteractions.getOrNull(index)
            
            // 应用所有技法加成，使用与厨师选择框相同的计算方式
            val enhancedChef = com.example.show_auto.utils.ChefSkillCalculator.applyAllSkills(
                chef, ultimateSkills, equip, skills, chefInteractionBonus
            )
            
            // 如果启用厨具遗玉，还需要应用心法盘技法值加成
            val finalEnhancedChef = if (settingsStorage.getCalculatorUsePersonalData() && personalData != null && gameData != null) {
                // 获取厨师的心法盘配置（使用厨师选择框中的配置）
                val chefAmbers = if (index < calculatorAmbers.size && calculatorAmbers[index].any { it != null }) {
                    // 使用厨师选择框中的心法盘配置
                    calculatorAmbers[index]
                } else {
                    // 如果没有厨师选择框配置，使用个人数据中的配置
                    val personalChef = personalData.chefs[chef.chefId]
                    if (personalChef?.ambers != null && personalChef.ambers.isNotEmpty()) {
                        val ambers = mutableListOf<com.example.show_auto.data.Amber?>()
                        personalChef.ambers.forEach { amberId ->
                            val amber = gameData.ambers.find { it.amberId == amberId.toString() }
                            ambers.add(amber)
                        }
                        // 确保有3个位置
                        while (ambers.size < 3) {
                            ambers.add(null)
                        }
                        ambers.take(3)
                    } else {
                        listOf(null, null, null)
                    }
                }
                
                // 获取厨师等级（使用厨师选择框中的等级）
                val chefLevel = if (index < calculatorLevels.size) calculatorLevels[index] ?: 1 else 1
                
                // 如果开启了心法盘默认满级，则对所有蓝色心法盘位置使用满朋陨
                val finalAmbers = if (settingsStorage.getCalculatorDefaultMaxLevelAmber()) {
                    applyMaxLevelAmberToBluePositions(chef, chefAmbers.toMutableList(), gameData, true)
                } else {
                    chefAmbers
                }
                
                // 计算心法盘技法值加成
                val techniqueValuesWithAmbers = calculateTechniqueValuesWithAmbers(chef, skills, gameData, chefLevel, finalAmbers, enhancedChef)
                
                // 创建包含心法盘加成的最终厨师数据
                enhancedChef.copy(
                    stirfry = techniqueValuesWithAmbers["stirfry"]?.second ?: enhancedChef.stirfry,
                    boil = techniqueValuesWithAmbers["boil"]?.second ?: enhancedChef.boil,
                    knife = techniqueValuesWithAmbers["knife"]?.second ?: enhancedChef.knife,
                    fry = techniqueValuesWithAmbers["fry"]?.second ?: enhancedChef.fry,
                    bake = techniqueValuesWithAmbers["bake"]?.second ?: enhancedChef.bake,
                    steam = techniqueValuesWithAmbers["steam"]?.second ?: enhancedChef.steam
                )
            } else {
                enhancedChef
            }
            
            enhancedChefsWithSkills.add(finalEnhancedChef)
            
            System.out.println("厨师 ${chef.name} 技法值计算完成: 炒${finalEnhancedChef.stirfry} 煮${finalEnhancedChef.boil} 切${finalEnhancedChef.knife} 炸${finalEnhancedChef.fry} 烤${finalEnhancedChef.bake} 蒸${finalEnhancedChef.steam}")
        }
        
        val existingResult = OneClickQueryResult(
            chefGroup = existingChefGroup,
            totalGuestRate = totalGuestRate,
            totalCritRate = finalCritRate,
            totalTimeBonus = finalTimeRate,
            unitTime = 0.0, // 这个值在菜谱分配时会重新计算
            hundredPotOutput = 0.0,
            unitFood = 0.0,
            recommendedRank = "特",
            enhancedChefs = enhancedChefsWithSkills
        )
        
        // 将现有厨师组合添加到结果列表中，供第二阶段使用
        results = listOf(existingResult)
        
        // 继续执行第二阶段的逻辑
        System.out.println("使用现有厨师组合继续执行菜谱分配逻辑")
    } else {
        System.out.println("游戏数据不为空，开始获取厨师信息")
        System.out.println("技能数量: ${skills.size}")
        System.out.println("个人数据: ${if (personalData != null) "不为空" else "为空"}")
        System.out.println("设置存储: ${if (settingsStorage != null) "不为空" else "为空"}")
        
        // 获取查询设置状态
        val isQueryEfficiencyMode = settingsStorage.getCalculatorQueryMode()
        System.out.println("当前查询模式: ${if (isQueryEfficiencyMode) "查询效率" else "查询必来"}")
        
        // 用于跟踪已选择的厨师ID，确保每步都不重复
        val selectedChefIds = mutableSetOf<String>()
        val allChefs = mutableListOf<com.example.show_auto.data.Chef>()
        
        // 步骤1：默认逻辑查询（取前3名）
        System.out.println("=== 步骤1：默认逻辑查询（取前3名） ===")
        val step1Chefs = getChefsByExistingLogic(
            gameData = gameData,
            skills = skills,
            personalData = personalData,
            settingsStorage = settingsStorage,
            onlyShowOwned = !useAllChefs, // 根据"使用全部厨师"设置判断
            onlyShowCritChefs = false,
            onlyShowAssassinChefs = false,
            defaultMaxLevelAmber = defaultMaxLevelAmber
        )
        
        // 从步骤1中取前3个不重复的厨师
        val step1Selected = mutableListOf<com.example.show_auto.data.Chef>()
        var step1Index = 0
        while (step1Selected.size < 3 && step1Index < step1Chefs.size) {
            val chef = step1Chefs[step1Index]
            if (!selectedChefIds.contains(chef.chefId)) {
                step1Selected.add(chef)
                selectedChefIds.add(chef.chefId)
                allChefs.add(chef)
            }
            step1Index++
        }
        
        System.out.println("步骤1获取到 ${step1Selected.size} 个厨师:")
        step1Selected.forEachIndexed { index, chef ->
            System.out.println("  厨师${index + 1}: ID=${chef.chefId}, 名称=${chef.name}, 星级=${chef.rarity}, 已拥有=${chef.got}, 已修炼=${chef.ult}")
        }
        
        // 步骤2：添加查询暴击条件（取前3名，排除已选择的）
        System.out.println("=== 步骤2：添加查询暴击条件（取前3名，排除已选择的） ===")
        val step2Chefs = getChefsByExistingLogic(
            gameData = gameData,
            skills = skills,
            personalData = personalData,
            settingsStorage = settingsStorage,
            onlyShowOwned = !useAllChefs, // 根据"使用全部厨师"设置判断
            onlyShowCritChefs = true,
            onlyShowAssassinChefs = false,
            defaultMaxLevelAmber = defaultMaxLevelAmber
        )
        
        // 从步骤2中取前3个不重复的厨师
        val step2Selected = mutableListOf<com.example.show_auto.data.Chef>()
        var step2Index = 0
        while (step2Selected.size < 3 && step2Index < step2Chefs.size) {
            val chef = step2Chefs[step2Index]
            if (!selectedChefIds.contains(chef.chefId)) {
                step2Selected.add(chef)
                selectedChefIds.add(chef.chefId)
                allChefs.add(chef)
            }
            step2Index++
        }
        
        System.out.println("步骤2获取到 ${step2Selected.size} 个厨师:")
        step2Selected.forEachIndexed { index, chef ->
            System.out.println("  厨师${index + 1}: ID=${chef.chefId}, 名称=${chef.name}, 星级=${chef.rarity}, 已拥有=${chef.got}, 已修炼=${chef.ult}")
        }
        
        // 根据查询设置决定是否执行第三步
        if (isQueryEfficiencyMode) {
            System.out.println("=== 步骤3：添加查询刺客条件（取前3名，排除已选择的）- 查询效率模式 ===")
            val step3Chefs = getChefsByExistingLogic(
                gameData = gameData,
                skills = skills,
                personalData = personalData,
                settingsStorage = settingsStorage,
                onlyShowOwned = !useAllChefs, // 根据"使用全部厨师"设置判断
                onlyShowCritChefs = false,
                onlyShowAssassinChefs = true,
                defaultMaxLevelAmber = defaultMaxLevelAmber
            )
            
            // 从步骤3中取前3个不重复的厨师
            val step3Selected = mutableListOf<com.example.show_auto.data.Chef>()
            var step3Index = 0
            while (step3Selected.size < 3 && step3Index < step3Chefs.size) {
                val chef = step3Chefs[step3Index]
                if (!selectedChefIds.contains(chef.chefId)) {
                    step3Selected.add(chef)
                    selectedChefIds.add(chef.chefId)
                    allChefs.add(chef)
                }
                step3Index++
            }
            
            System.out.println("步骤3获取到 ${step3Selected.size} 个厨师:")
            step3Selected.forEachIndexed { index, chef ->
                System.out.println("  厨师${index + 1}: ID=${chef.chefId}, 名称=${chef.name}, 星级=${chef.rarity}, 已拥有=${chef.got}, 已修炼=${chef.ult}")
            }
        } else {
            System.out.println("=== 步骤3：跳过（查询必来模式，只使用前两步筛选结果） ===")
        }
        
        System.out.println("最终筛选结果，总共 ${allChefs.size} 个厨师")
        System.out.println("筛选模式: ${if (isQueryEfficiencyMode) "查询效率（三步筛选）" else "查询必来（两步筛选）"}")
        System.out.println("已选择的厨师ID: ${selectedChefIds.toList().sorted()}")
        
        // 打印去重后的厨师信息
        allChefs.forEachIndexed { index, chef ->
            System.out.println("去重后厨师${index + 1}: ID=${chef.chefId}, 名称=${chef.name}, 星级=${chef.rarity}, 已拥有=${chef.got}, 已修炼=${chef.ult}")
        }
        
        // 生成厨师组合（3个厨师一组）
        val chefGroups = generateChefCombinations(allChefs)
        
        System.out.println("=== 厨师分组信息 ===")
        System.out.println("分组总数: ${chefGroups.size}")
        
        // 打印每组厨师信息（只打印前10组，避免日志过多）
        chefGroups.take(10).forEachIndexed { groupIndex, group ->
            System.out.println("第${groupIndex + 1}组:")
            
            // 计算该组的总加成
            var totalGuestRate = 0.0
            var totalCritRate = 0.0
            var totalTimeBonus = 0.0
            
            group.forEachIndexed { chefIndex, chef ->
                // 根据"启用厨具遗玉"设置决定是否获取厨具数据
                val chefEquip = if (settingsStorage.getCalculatorUsePersonalData() && personalData != null && gameData != null) {
                    val equipId = personalData.chefs[chef.chefId]?.equip
                    if (equipId != null) {
                        gameData.equips.find { it.equipId == equipId.toString() }
                    } else {
                        null
                    }
                } else {
                    null
                }
                
                // 根据"启用厨具遗玉"设置决定是否使用个人数据计算加成
                val guestRateBonus = if (settingsStorage.getCalculatorUsePersonalData()) {
                    calculateTotalGuestRateBonusWithMaxAmber(chef, skills, gameData, personalData, settingsStorage.getCalculatorDefaultMaxLevelAmber(), settingsStorage.getCalculatorDefaultAllUltimate())
                } else {
                    // 当"启用厨具遗玉"关闭时，不使用个人数据中的厨具和心法盘，但使用心法盘默认满级设置
                    val useMaxLevelAmber = settingsStorage.getCalculatorDefaultMaxLevelAmber()
                    calculateTotalGuestRateBonusWithMaxAmber(chef, skills, gameData, null, useMaxLevelAmber, settingsStorage.getCalculatorDefaultAllUltimate())
                }
                
                // 根据"启用厨具遗玉"设置决定是否使用个人数据计算暴击率
                val critRateBonus = if (settingsStorage.getCalculatorUsePersonalData()) {
                    calculateTotalCritRateForCalculator(chef, skills, gameData, personalData, settingsStorage.getCalculatorDefaultAllUltimate()) - 100.0
                } else {
                    // 当"启用厨具遗玉"关闭时，不使用个人数据中的厨具和心法盘，但使用心法盘默认满级设置
                    // 注意：暴击率计算函数不直接支持心法盘默认满级，但会通过贵客率计算间接影响
                    calculateTotalCritRateForCalculator(chef, skills, gameData, null, settingsStorage.getCalculatorDefaultAllUltimate()) - 100.0
                }
                
                // 根据"启用厨具遗玉"设置决定是否使用个人数据计算时间加成
                val timeBonus = if (settingsStorage.getCalculatorUsePersonalData()) {
                    calculateOpeningTimeBonus(chef, chefEquip, skills, gameData, personalData, settingsStorage.getCalculatorDefaultAllUltimate())
                } else {
                    // 当"启用厨具遗玉"关闭时，不使用个人数据中的厨具和心法盘，但使用心法盘默认满级设置
                    // 注意：时间加成计算函数不直接支持心法盘默认满级，但会通过贵客率计算间接影响
                    calculateOpeningTimeBonus(chef, null, skills, gameData, null, settingsStorage.getCalculatorDefaultAllUltimate())
                }
                
                totalGuestRate += guestRateBonus
                totalCritRate += critRateBonus
                totalTimeBonus += timeBonus
                
                System.out.println("  厨师${chefIndex + 1}: ${chef.name}(ID:${chef.chefId}, 星级:${chef.rarity}) - 贵客率:${String.format("%.2f", guestRateBonus)}%, 暴击率:${String.format("%.2f", critRateBonus)}%, 时间:${String.format("%.2f", timeBonus)}%")
            }
            
            // 计算最终的总值
            val finalCritRate = 100.0 + totalCritRate
            // 注意：totalTimeBonus中，正值表示增加时间，负值表示减少时间
            // 所以最终时间应该是：100 + totalTimeBonus
            val finalTimeRate = 100.0 + totalTimeBonus
            
            System.out.println("  组总加成 - 总贵客率:${String.format("%.2f", totalGuestRate)}%, 总暴击率:${String.format("%.2f", finalCritRate)}%, 时间:${String.format("%.2f", finalTimeRate)}%")
            System.out.println("")
        }
        
        if (chefGroups.size > 10) {
            System.out.println("... 还有${chefGroups.size - 10}组未显示")
        }
        
        // 批量计算每组的结果
        System.out.println("=== 开始批量计算 ===")
        results = calculateAllChefGroups(
            chefGroups = chefGroups,
            skills = skills,
            gameData = gameData,
            personalData = personalData,
            settingsStorage = settingsStorage,
            ultimateSkills = ultimateSkills
        )
    }
   
    // === 第二阶段：符文菜谱查询和厨师组合筛选 ===
    
    // 获取查询设置中所有勾选的符文名称
    val selectedRunes = mutableSetOf<String>()
    
    // 获取金符文选择
    val goldRunes = listOf("恐怖利刃", "鼓风机", "蒸馏杯", "千年煮鳖", "香烤鱼排", "五星炒果")
    val selectedGoldRunes = settingsStorage.getGoldRuneSelections()
    selectedGoldRunes.forEach { rune ->
        if (goldRunes.contains(rune)) {
            selectedRunes.add(rune)
        }
    }
    
    // 获取银符文选择
    val silverRunes = listOf("刀嘴鹦鹉", "一昧真火", "蒸汽宝石", "耐煮的水草", "焦虫", "暖石")
    val selectedSilverRunes = settingsStorage.getSilverRuneSelections()
    selectedSilverRunes.forEach { rune ->
        if (silverRunes.contains(rune)) {
            selectedRunes.add(rune)
        }
    }
    
    // 获取铜符文选择
    val bronzeRunes = listOf("剪刀蟹", "油火虫", "蒸汽耳环", "防水的柠檬", "烤焦的菊花", "五香果")
    val selectedBronzeRunes = settingsStorage.getBronzeRuneSelections()
    selectedBronzeRunes.forEach { rune ->
        if (bronzeRunes.contains(rune)) {
            selectedRunes.add(rune)
        }
    }
    
    // 根据符文选择情况决定厨师组合筛选策略
    var bestResult: OneClickQueryResult? = null
    
    if (selectedRunes.isNotEmpty()) {
        System.out.println("=== 检测到符文选择，开始智能厨师组合筛选 ===")
        
        // 获取最优厨师组合（按单位时间排序）
        val bestChefGroup = results.maxByOrNull { it.unitTime }
        System.out.println("使用最优厨师组合进行菜谱分配测试")
        
        if (bestChefGroup != null) {
            System.out.println("最优组合详情:")
            System.out.println("  单位时间: ${String.format("%.2f", bestChefGroup.unitTime)}")
            System.out.println("  总贵客率: ${String.format("%.2f", bestChefGroup.totalGuestRate)}%")
            System.out.println("  总暴击率: ${String.format("%.2f", bestChefGroup.totalCritRate)}%")
            System.out.println("  时间加成: ${String.format("%.2f", bestChefGroup.totalTimeBonus)}%")
            System.out.println("  厨师组合:")
            bestChefGroup.chefGroup.forEachIndexed { chefIndex, chef ->
                System.out.println("    厨师${chefIndex + 1}: ${chef.name} (ID:${chef.chefId}, 星级:${chef.rarity})")
            }
            System.out.println("")
        }
        
        // 调用查询贵客冲突页面的一键查询接口，获取符文菜谱
        val runeRecipes = queryRuneRecipesByMultipleRunes(selectedRunes.toList(), gameData, skills)
        
        if (runeRecipes.isNotEmpty()) {
            System.out.println("符文菜谱查询完成，共 ${runeRecipes.size} 个无冲突的已拥有菜谱")
            
            // 按符文分类菜谱
            val recipesByRune = mutableMapOf<String, MutableList<com.example.show_auto.data.Recipe>>()
            selectedRunes.forEach { rune ->
                recipesByRune[rune] = mutableListOf()
            }
            
            // 将菜谱按符文分类
            runeRecipes.forEach { recipe ->
                selectedRunes.forEach { rune ->
                    // 检查该菜谱是否与选中的符文相关
                    val isRelated = gameData.guests.any { guest ->
                        guest.gifts.any { gift ->
                            gift.antique == rune && gift.recipe == recipe.name
                        }
                    }
                    if (isRelated) {
                        recipesByRune[rune]?.add(recipe)
                    }
                }
            }
            
            // 打印按符文分类的菜谱列表
            System.out.println("=== 按符文分类的菜谱列表 ===")
            recipesByRune.forEach { (rune, recipes) ->
                System.out.println("符文: $rune (共${recipes.size}个菜谱)")
                recipes.sortedBy { it.time }.forEachIndexed { index, recipe ->
                    System.out.println("  ${index + 1}. ${recipe.name} (${recipe.rarity}星, 时间:${recipe.time}秒)")
                }
                System.out.println("")
            }
            
            // 开始菜谱分配算法
            val bestAllocationResult = if (bestChefGroup != null) {
                findBestRecipeAllocation(
                    top10Results = listOf(bestChefGroup),
                    selectedRunes = selectedRunes.toList(),
                    recipesByRune = recipesByRune,
                    gameData = gameData,
                    skills = skills,
                    personalData = personalData,
                    settingsStorage = settingsStorage,
                    recipeLimits = recipeLimits
                )
            } else {
                null
            }
            
            if (bestAllocationResult != null) {
                System.out.println("找到最优菜谱分配方案")
                
                // 打印每个厨师的菜谱分配详情
                System.out.println("=== 厨师菜谱分配详情 ===")
                bestAllocationResult.chefGroup.forEachIndexed { chefIndex, chef ->
                    val chefAllocatedRecipes = bestAllocationResult.allocatedRecipes.filter { it.assignedChef.chefId == chef.chefId }
                    if (chefAllocatedRecipes.isNotEmpty()) {
                        System.out.println("厨师 ${chef.name} (ID:${chef.chefId}, 星级:${chef.rarity}):")
                        var chefTotalTime = 0
                        chefAllocatedRecipes.forEachIndexed { recipeIndex, allocatedRecipe ->
                            val singleTime = allocatedRecipe.recipe.time
                            val totalTime = allocatedRecipe.cookingTime
                            val singleTimeFormatted = formatTime(singleTime)
                            val totalTimeFormatted = formatTime(totalTime)
                            System.out.println("  ${recipeIndex + 1}. ${allocatedRecipe.recipe.name} (符文:${allocatedRecipe.rune}, 品级:${allocatedRecipe.quality}, 份数:${allocatedRecipe.quantity}, 单份时间:${singleTime}秒${singleTimeFormatted}, 总份数时间:${totalTime}秒${totalTimeFormatted})")
                            chefTotalTime += totalTime
                        }
                        val chefTotalTimeFormatted = formatTime(chefTotalTime)
                        System.out.println("  小计: ${chefAllocatedRecipes.size}道菜谱, 总时间:${chefTotalTime}秒${chefTotalTimeFormatted}")
                    } else {
                        System.out.println("厨师 ${chef.name} (ID:${chef.chefId}, 星级:${chef.rarity}): 未分配菜谱")
                    }
                }
                
                // 打印总体分配统计
                System.out.println("=== 总体分配统计 ===")
                System.out.println("总菜谱数量: ${bestAllocationResult.allocatedRecipes.size}")
                val totalTimeFormatted = formatTime(bestAllocationResult.totalCookingTime)
                System.out.println("总制作时间: ${bestAllocationResult.totalCookingTime}秒${totalTimeFormatted} (${String.format("%.1f", bestAllocationResult.totalCookingTime / 3600.0)}小时)")
                System.out.println("总贵客率: ${bestAllocationResult.totalGuestRate}%")
                System.out.println("总暴击率: ${bestAllocationResult.totalCritRate}%")
                System.out.println("总时间加成: ${bestAllocationResult.totalTimeBonus}%")
                
                // 将分配的菜谱按厨师槽位分组，传递给菜谱更新回调
                val recipesByChef = mutableMapOf<Int, MutableList<com.example.show_auto.data.Recipe>>()
                
                // 初始化每个厨师槽位的菜谱列表
                repeat(3) { chefIndex ->
                    recipesByChef[chefIndex] = mutableListOf()
                }
                
                // 将菜谱按厨师分组
                bestAllocationResult.allocatedRecipes.forEach { allocatedRecipe ->
                    val chefIndex = bestAllocationResult.chefGroup.indexOfFirst { it.chefId == allocatedRecipe.assignedChef.chefId }
                    if (chefIndex >= 0) {
                        recipesByChef[chefIndex]?.add(allocatedRecipe.recipe)
                    }
                }
                
                onRecipeUpdate(recipesByChef, bestAllocationResult.totalGuestRate)
                System.out.println("已调用菜谱更新回调，按厨师槽位分配菜谱:")
                recipesByChef.forEach { (chefIndex, recipes) ->
                    System.out.println("  厨师槽位$chefIndex: ${recipes.map { it.name }}")
                }
                
                // 使用最优分配方案，需要创建一个OneClickQueryResult对象
                bestResult = OneClickQueryResult(
                    chefGroup = bestAllocationResult.chefGroup,
                    totalGuestRate = bestAllocationResult.totalGuestRate,
                    totalCritRate = bestAllocationResult.totalCritRate,
                    totalTimeBonus = bestAllocationResult.totalTimeBonus,
                    unitTime = bestAllocationResult.unitTime,
                    hundredPotOutput = bestAllocationResult.hundredPotOutput,
                    unitFood = bestAllocationResult.unitFood,
                    recommendedRank = "特", // 默认推荐特级
                    enhancedChefs = bestAllocationResult.enhancedChefs
                )
            } else {
                System.out.println("未找到合适的菜谱分配方案，使用默认最优组合")
                bestResult = results.maxByOrNull { it.unitTime }
                // 没有菜谱分配时，传递空的分组映射
                onRecipeUpdate(emptyMap(), 0.0)
                System.out.println("未找到菜谱分配方案，菜谱列表已清空")
            }
            
        } else {
            System.out.println("未查询到符文菜谱，使用默认最优组合")
            bestResult = results.maxByOrNull { it.unitTime }
            // 没有符文菜谱时，传递空的分组映射
            onRecipeUpdate(emptyMap(), 0.0)
            System.out.println("未查询到符文菜谱，菜谱列表已清空")
        }
        
    } else {
        System.out.println("=== 无符文选择，使用默认最优组合 ===")
        // 找出单位时间最优的组合
        bestResult = results.maxByOrNull { it.unitTime }
        // 无符文选择时，传递空的分组映射
        onRecipeUpdate(emptyMap(), 0.0)
        System.out.println("无符文选择，菜谱列表已清空")
    }
    
    System.out.println("一键查询执行完成")
    
    // 设置计算结果到UI状态
    onResultUpdate(bestResult)
    onProgressUpdate(false)
    
    // 自动填充最优组合到选择框
    if (bestResult != null) {
        // 当场上有厨师时，只更新菜谱UI，不更新厨师选择框UI
        if (existingChefs.isEmpty()) {
            // 没有场上厨师时，才更新厨师选择框
            System.out.println("场上无厨师，更新厨师选择框UI")
            
            // 更新厨师选择
            val updatedChefs = mutableListOf<com.example.show_auto.data.Chef>()
            val updatedEquips = mutableListOf<com.example.show_auto.data.Equip>()
            val updatedAmbers = mutableListOf<List<com.example.show_auto.data.Amber?>>()
            val updatedLevels = mutableListOf<Int>()
            
            bestResult.chefGroup.forEach { chef ->
                updatedChefs.add(chef)
                
                // 根据"启用厨具遗玉"设置决定是否更新厨具、心法盘和等级
                if (settingsStorage.getCalculatorUsePersonalData()) {
                    // 当"启用厨具遗玉"开启时，自动设置厨具、心法盘和等级
                    
                    // 获取该厨师的厨具
                    val chefEquip = if (personalData != null) {
                        val equipId = personalData.chefs[chef.chefId]?.equip
                        if (equipId != null && gameData != null) {
                            gameData.equips.find { it.equipId == equipId.toString() }
                        } else {
                            null
                        }
                    } else {
                        null
                    }
                    updatedEquips.add(chefEquip ?: com.example.show_auto.data.Equip())
                    
                    // 获取该厨师的心法盘
                    val chefAmbers = if (personalData != null && gameData != null) {
                        val personalChef = personalData.chefs[chef.chefId]
                        if (personalChef?.ambers != null && personalChef.ambers.isNotEmpty()) {
                            val ambers = mutableListOf<com.example.show_auto.data.Amber?>()
                            personalChef.ambers.forEach { amberId ->
                                val amber = gameData.ambers.find { it.amberId == amberId.toString() }
                                ambers.add(amber)
                            }
                            // 确保有3个位置
                            while (ambers.size < 3) {
                                ambers.add(null)
                            }
                            ambers.take(3)
                        } else {
                            listOf(null, null, null)
                        }
                    } else {
                        listOf(null, null, null)
                    }
                    
                    // 如果开启了心法盘默认满级，则对所有蓝色心法盘位置使用满朋陨
                    val finalAmbers = if (defaultMaxLevelAmber && gameData != null) {
                        applyMaxLevelAmberToBluePositions(chef, chefAmbers.toMutableList(), gameData, true)
                    } else {
                        chefAmbers
                    }
                    
                    updatedAmbers.add(finalAmbers)
                    
                    // 设置等级：如果开启心法盘默认满级，则根据厨师星级设置满级
                    val level = if (defaultMaxLevelAmber) {
                        when (chef.rarity) {
                            5 -> 5
                            4 -> 4
                            else -> 3
                        }
                    } else if (personalData != null) {
                        val personalChef = personalData.chefs[chef.chefId]
                        personalChef?.dlv ?: 1
                    } else {
                        1
                    }
                    updatedLevels.add(level)
                } else {
                    // 当"启用厨具遗玉"关闭时，不更新厨具、心法盘和等级，保持用户之前的选择
                    // 但是，如果开启了心法盘默认满级，即使"启用厨具遗玉"关闭，也要设置满级满朋陨
                    updatedEquips.add(com.example.show_auto.data.Equip())
                    
                    if (defaultMaxLevelAmber && gameData != null) {
                        // 创建默认的心法盘列表（空的心法盘）
                        val defaultAmbers = mutableListOf<com.example.show_auto.data.Amber?>(null, null, null)
                        
                        // 对所有蓝色心法盘位置使用满朋陨
                        val finalAmbers = applyMaxLevelAmberToBluePositions(chef, defaultAmbers, gameData, true)
                        
                        // 调试信息：输出心法盘更新信息
                        System.out.println("厨师 ${chef.name} 心法盘默认满级开启，应用满朋陨:")
                        System.out.println("  原始心法盘: $defaultAmbers")
                        System.out.println("  最终心法盘: $finalAmbers")
                        
                        updatedAmbers.add(finalAmbers)
                        
                        // 根据厨师星级设置心法盘等级
                        val level = when (chef.rarity) {
                            5 -> 5
                            4 -> 4
                            else -> 3
                        }
                        updatedLevels.add(level)
                        
                        System.out.println("  设置等级: $level")
                    } else {
                        // 不改变当前心法盘选择，保持用户之前的选择
                        updatedAmbers.add(listOf(null, null, null))
                        updatedLevels.add(1) // 默认等级，但不影响UI显示
                    }
                }
            }
            
            // 调用选择框更新回调，传递品级信息
            // 检查最优组合中是否有"场上厨师制作特级及以上料理时此料理贵客符文概率+%"类技能
            val hasSpecialRuneSkill = bestResult.chefGroup.any { chef ->
                // 获取厨师的基础技能描述
                val baseSkillDesc = if (chef.skill > 0) {
                    skills.find { it.skillId == chef.skill }?.desc ?: ""
                } else {
                    ""
                }
                
                // 获取厨师的修炼技能描述（使用override版本，确保未拥有厨师也能正确计算修炼技能）
                val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(chef, skills, settingsStorage.getCalculatorDefaultAllUltimate())
                val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
                
                // 检查是否包含"场上厨师制作特级及以上料理时此料理贵客符文概率+%"类技能
                val specialSkillPattern = "场上厨师制作特级及以上料理时此料理贵客符文概率\\+(\\d+(?:\\.\\d+)?)%"
                specialSkillPattern.toRegex().find(combinedSkillDesc) != null
            }
            
            val recommendedRank = if (hasSpecialRuneSkill) "特" else "可" // 如果有特殊技能，推荐特级
            onSelectionUpdate(updatedChefs, updatedEquips, updatedAmbers, updatedLevels, recommendedRank)
        } else {
            System.out.println("场上有厨师，跳过厨师选择框UI更新，只更新菜谱UI")
        }
    }
}

/**
 * 计算厨师制作菜谱的最终品级
 * @param chef 厨师（已包含最终技法值）
 * @param recipe 菜谱
 * @return 最终品级
 */
private fun calculateRecipeQuality(
    chef: com.example.show_auto.data.Chef,
    recipe: com.example.show_auto.data.Recipe
): String {
    // 使用 RecipeRankCalculator 计算品级
    val rank = com.example.show_auto.utils.RecipeRankCalculator.calculateRecipeRank(chef, recipe)
    
    // 转换为品级文本
    return when (rank) {
        0 -> "无法制作"
        1 -> "可"
        2 -> "优"
        3 -> "特"
        4 -> "神"
        5 -> "传"
        else -> "可"
    }
}

/**
 * 检查品级是否满足要求
 * @param actualQuality 实际品级
 * @param requiredQuality 要求品级
 * @return 是否满足要求
 */
private fun isQualitySufficient(actualQuality: String, requiredQuality: String): Boolean {
    val qualityOrder = listOf("神", "特", "优", "可")
    val actualIndex = qualityOrder.indexOf(actualQuality)
    val requiredIndex = qualityOrder.indexOf(requiredQuality)
    
    return actualIndex <= requiredIndex // 品级越高，索引越小
}

/**
 * 计算菜谱分配份数
 * @param quality 品级
 * @param totalGuestRate 总贵客率
 * @param settingsStorage 设置存储
 * @return 分配份数
 */
private fun calculateRecipeQuantity(
    recipe: com.example.show_auto.data.Recipe,
    totalGuestRate: Double,
    settingsStorage: com.example.show_auto.data.SettingsStorage,
    isSupplemented: Boolean = false,
    recipeLimits: com.example.show_auto.ui.pages.RecipeLimitsState? = null
): Int {
    // 如果是强补菜谱，份数始终为1
    if (isSupplemented) {
        System.out.println("calculateRecipeQuantity: 强补菜谱=${recipe.name}, 份数固定为1")
        return 1
    }
    
    // 根据查询模式计算份数
    val isQueryEfficiencyMode = settingsStorage.getCalculatorQueryMode()
    
    System.out.println("calculateRecipeQuantity: 菜谱=${recipe.name}, 星级=${recipe.rarity}, 贵客率=$totalGuestRate%, 查询模式=${if (isQueryEfficiencyMode) "查询效率" else "查询必来"}")
    
    if (isQueryEfficiencyMode) {
        // 查询效率模式：根据菜谱星级固定份数
        val quantity = when (recipe.rarity) {
            5 -> 7   // 五星菜谱7份
            4 -> 10  // 四星菜谱10份
            3 -> 12  // 三星菜谱12份
            2 -> 15  // 二星菜谱15份
            1 -> 20  // 一星菜谱20份
            else -> 20 // 默认20份
        }
        System.out.println("  查询效率模式: ${recipe.rarity}星菜谱 -> ${quantity}份")
        return quantity
    } else {
                    // 查询必来模式：根据菜谱星级和贵客率查表确定份数
        val requiredPortions = getRequiredPortionsForStarLevel(totalGuestRate, recipe.rarity)
        System.out.println("  查询必来模式: ${recipe.rarity}星菜谱, 贵客率${totalGuestRate}% -> 必来份数${requiredPortions}份")
        
        // 如果有个人份数上限设置，则取较小值
        if (recipeLimits != null) {
            val personalLimit = when (recipe.rarity) {
                5 -> 15 + recipeLimits.star5
                4 -> 20 + recipeLimits.star4
                3 -> 25 + recipeLimits.star3
                2 -> 30 + recipeLimits.star2
                1 -> 40 + recipeLimits.star1
                else -> 40 + recipeLimits.star1
            }
            
            val finalQuantity = minOf(requiredPortions, personalLimit)
            
            // 计算基础份数和额外份数用于日志显示
            val basePortions = when (recipe.rarity) {
                5 -> 15
                4 -> 20
                3 -> 25
                2 -> 30
                1 -> 40
                else -> 40
            }
            val extraPortions = when (recipe.rarity) {
                5 -> recipeLimits.star5
                4 -> recipeLimits.star4
                3 -> recipeLimits.star3
                2 -> recipeLimits.star2
                1 -> recipeLimits.star1
                else -> recipeLimits.star1
            }
            
            System.out.println("    个人份数上限: ${personalLimit}份 (基础${basePortions} + 额外${extraPortions})")
            System.out.println("    最终份数: ${finalQuantity}份 (取必来份数${requiredPortions}和个人上限${personalLimit}的较小值)")
            return finalQuantity
        } else {
            System.out.println("    未设置个人份数上限，使用必来份数: ${requiredPortions}份")
            return requiredPortions
        }
    }
}

/**
 * 星级菜谱限制信息数据类
 */
data class StarLevelLimit(
    val starLevel: Int,
    val personalLimit: Int,
    val requiredPortions: Int,
    val requiredGuestRate: Double
)

/**
 * 贵客必来份数限制信息数据类
 */
data class GuestArrivalLimitInfo(
    val currentGuestRate: Double,
    val starLimits: List<StarLevelLimit>
)



/**
 * 贵客必来份数限制提示弹窗
 */
@Composable
private fun GuestArrivalLimitDialog(
    limitInfo: GuestArrivalLimitInfo,
    onDismiss: () -> Unit,
    onShowGuestRateTable: () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text(
                text = "当前贵客率无法达到贵客必来！",
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.error
            )
        },
        text = {
            Column(
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                Spacer(modifier = Modifier.height(8.dp))
                
                // 当前状态
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(
                        containerColor = MaterialTheme.colorScheme.surfaceVariant
                    )
                ) {
                    Column(
                        modifier = Modifier.padding(16.dp),
                        verticalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        Text(
                            text = "当前状态",
                            fontSize = 14.sp,
                            fontWeight = FontWeight.Medium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                        Text(
                            text = "• 当前贵客率: ${String.format("%.1f", limitInfo.currentGuestRate)}%",
                            fontSize = 13.sp,
                            color = MaterialTheme.colorScheme.onSurface
                        )
                        // 显示所有无法实现必来的星级限制
                        limitInfo.starLimits.forEach { starLimit ->
                            Text(
                                text = "• 个人${starLimit.starLevel}星菜谱上限份数: ${starLimit.personalLimit}份",
                                fontSize = 13.sp,
                                color = MaterialTheme.colorScheme.onSurface
                            )
                        }
                    }
                }
                
                // 解决方案
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(
                        containerColor = MaterialTheme.colorScheme.primaryContainer
                    )
                ) {
                    Column(
                        modifier = Modifier.padding(16.dp),
                        verticalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.SpaceBetween
                        ) {
                            Text(
                                text = "解决方案",
                                fontSize = 14.sp,
                                fontWeight = FontWeight.Medium,
                                color = MaterialTheme.colorScheme.onPrimaryContainer
                            )
                            
                            // 贵客必来对照表按钮
                            OutlinedButton(
                                onClick = onShowGuestRateTable,
                                modifier = Modifier.height(20.dp),
                                colors = ButtonDefaults.outlinedButtonColors(
                                    containerColor = MaterialTheme.colorScheme.secondaryContainer,
                                    contentColor = MaterialTheme.colorScheme.onSecondaryContainer
                                ),
                                shape = RoundedCornerShape(4.dp),
                                border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
                                contentPadding = PaddingValues(horizontal = 4.dp, vertical = 0.dp)
                            ) {
                                Text(
                                    text = "贵客必来对照表",
                                    fontSize = 9.sp,
                                    fontWeight = FontWeight.Medium,
                                    textAlign = TextAlign.Center
                                )
                            }
                        }
                        // 显示所有星级的解决方案
                        limitInfo.starLimits.forEach { starLimit ->
                            Text(
                                text = "• 提升贵客率到 ${String.format("%.1f", starLimit.requiredGuestRate)}% (还差 ${String.format("%.1f", starLimit.requiredGuestRate - limitInfo.currentGuestRate)}%)",
                                fontSize = 13.sp,
                                color = MaterialTheme.colorScheme.onPrimaryContainer
                            )
                            Text(
                                text = "• 或提升${starLimit.starLevel}星菜谱份数到 ${starLimit.requiredPortions}份",
                                fontSize = 13.sp,
                                color = MaterialTheme.colorScheme.onPrimaryContainer
                            )
                            Spacer(modifier = Modifier.height(4.dp))
                        }
                    }
                }
                

            }
        },
        confirmButton = {
            TextButton(
                onClick = onDismiss,
                colors = ButtonDefaults.textButtonColors(
                    contentColor = MaterialTheme.colorScheme.primary
                )
            ) {
                Text("我知道了")
            }
        },
        containerColor = MaterialTheme.colorScheme.surface,
        shape = RoundedCornerShape(16.dp)
    )
}

/**
 * 计算制作时间
 * @param baseTime 基础制作时间（秒）
 * @param quantity 份数
 * @param timeBonus 时间加成百分比
 * @return 总制作时间（秒）
 */
private fun calculateCookingTime(baseTime: Int, quantity: Int, timeBonus: Double): Int {
    val totalTime = baseTime * quantity
    System.out.println("calculateCookingTime: 单份时间=${baseTime}秒, 份数=${quantity}, 时间加成=${timeBonus}%, 基础总时间=${totalTime}秒")
    
    // 时间加成计算：timeBonus已经是百分比形式（如80.0表示80%）
    // 如果timeBonus是80.0，表示时间减少到80%，即乘以0.8
    val adjustedTime = totalTime * (timeBonus / 100.0)
    val finalTime = kotlin.math.ceil(adjustedTime).toInt()
    
    System.out.println("calculateCookingTime: 调整后时间=${adjustedTime}秒, 最终时间=${finalTime}秒")
    System.out.println("calculateCookingTime: 验证计算: ${baseTime} × ${quantity} × (${timeBonus}% ÷ 100) = ${totalTime} × ${timeBonus/100.0} = ${adjustedTime}")
    
    return finalTime
}

/**
 * 查找最优菜谱分配方案
 * @param top10Results 前10个厨师组合结果
 * @param selectedRunes 选中的符文列表
 * @param recipesByRune 按符文分类的菜谱列表
 * @param gameData 游戏数据
 * @param skills 技能数据
 * @param personalData 个人数据
 * @param settingsStorage 设置存储
 * @return 最优菜谱分配方案，如果没有找到则返回null
 */
private fun findBestRecipeAllocation(
    top10Results: List<OneClickQueryResult>,
    selectedRunes: List<String>,
    recipesByRune: Map<String, List<com.example.show_auto.data.Recipe>>,
    gameData: com.example.show_auto.data.GameData,
    skills: List<com.example.show_auto.data.Skill>,
    personalData: com.example.show_auto.data.PersonalData?,
    settingsStorage: com.example.show_auto.data.SettingsStorage,
    recipeLimits: com.example.show_auto.ui.pages.RecipeLimitsState
): RecipeAllocationResult? {
    System.out.println("开始查找最优菜谱分配方案")
    System.out.println("厨师组合数量: ${top10Results.size}")
    System.out.println("选中符文: ${selectedRunes.joinToString(", ")}")
    System.out.println("符文菜谱分类: ${recipesByRune.mapValues { it.value.size }}")
    
    // 使用最优组合进行菜谱分配
    val bestChefGroup = top10Results.first()
    System.out.println("使用最优组合进行菜谱分配:")
    
    // 直接使用预计算的技法值，避免重复计算
    val enhancedChefs = if (bestChefGroup.enhancedChefs.isNotEmpty()) {
        bestChefGroup.enhancedChefs
    } else {
        // 如果没有预计算的技法值，则重新计算（兼容性处理）
        val fallbackEnhancedChefs = mutableListOf<com.example.show_auto.data.Chef>()
        bestChefGroup.chefGroup.forEachIndexed { index, chef ->
            // 获取该厨师当前佩戴的厨具
            val chefEquip = if (personalData != null) {
                val equipId = personalData.chefs[chef.chefId]?.equip
                if (equipId != null) {
                    gameData.equips.find { it.equipId == equipId.toString() }
                } else {
                    null
                }
            } else {
                null
            }
            
            // 计算厨师间技法影响
            val chefInteractions = com.example.show_auto.utils.ChefInteractionCalculator.calculateChefInteractions(
                bestChefGroup.chefGroup, skills, settingsStorage.getSelectedAuraChefs()
            )
            val chefInteractionBonus = chefInteractions.getOrNull(index)
            
            // 应用所有技法加成
            val enhancedChef = com.example.show_auto.utils.ChefSkillCalculator.applyAllSkills(
                chef, UltimateSkillsState(), chefEquip, skills, chefInteractionBonus
            )
            
            // 如果启用厨具遗玉，还需要应用心法盘技法值加成
            val finalEnhancedChef = if (settingsStorage.getCalculatorUsePersonalData() && personalData != null && gameData != null) {
                // 获取厨师的心法盘配置
                val personalChef = personalData.chefs[chef.chefId]
                val chefAmbers = if (personalChef?.ambers != null && personalChef.ambers.isNotEmpty()) {
                    val ambers = mutableListOf<com.example.show_auto.data.Amber?>()
                    personalChef.ambers.forEach { amberId ->
                        val amber = gameData.ambers.find { it.amberId == amberId.toString() }
                        ambers.add(amber)
                    }
                    // 确保有3个位置
                    while (ambers.size < 3) {
                        ambers.add(null)
                    }
                    ambers.take(3)
                } else {
                    listOf(null, null, null)
                }
                
                // 获取厨师等级
                val chefLevel = personalChef?.dlv ?: 1
                
                // 如果开启了心法盘默认满级，则对所有蓝色心法盘位置使用满朋陨
                val finalAmbers = if (settingsStorage.getCalculatorDefaultMaxLevelAmber()) {
                    applyMaxLevelAmberToBluePositions(chef, chefAmbers.toMutableList(), gameData, true)
                } else {
                    chefAmbers
                }
                
                // 计算心法盘技法值加成
                val techniqueValuesWithAmbers = calculateTechniqueValuesWithAmbers(chef, skills, gameData, chefLevel, finalAmbers, enhancedChef)
                
                // 创建包含心法盘加成的最终厨师数据
                enhancedChef.copy(
                    stirfry = techniqueValuesWithAmbers["stirfry"]?.second ?: enhancedChef.stirfry,
                    boil = techniqueValuesWithAmbers["boil"]?.second ?: enhancedChef.boil,
                    knife = techniqueValuesWithAmbers["knife"]?.second ?: enhancedChef.knife,
                    fry = techniqueValuesWithAmbers["fry"]?.second ?: enhancedChef.fry,
                    bake = techniqueValuesWithAmbers["bake"]?.second ?: enhancedChef.bake,
                    steam = techniqueValuesWithAmbers["steam"]?.second ?: enhancedChef.steam
                )
            } else {
                enhancedChef
            }
            
            fallbackEnhancedChefs.add(finalEnhancedChef)
        }
        fallbackEnhancedChefs
    }
    
    // 打印每个厨师的技法值信息
    enhancedChefs.forEachIndexed { index, enhancedChef ->
        val chef = bestChefGroup.chefGroup[index]
        System.out.println("  厨师${index + 1}: ${chef.name} (ID:${chef.chefId}, 星级:${chef.rarity})")
        System.out.println("    最终技法值: 炒:${enhancedChef.stirfry}, 煮:${enhancedChef.boil}, 刀:${enhancedChef.knife}, 炸:${enhancedChef.fry}, 烤:${enhancedChef.bake}, 蒸:${enhancedChef.steam}")
    }
    
    // 开始菜谱分配算法
    val allocatedRecipes = mutableListOf<AllocatedRecipe>()
    var totalCookingTime = 0
    
    // 获取时间限制设置
    val timeLimitHours = settingsStorage.getCalculatorDefaultTime()
    val timeLimitSeconds = (timeLimitHours * 3600).toInt()
    
    // 第一轮分配：按符文评分排序分配菜谱
    var shouldStopFirstRound = false
    
    // 计算每种符文的最高评分菜谱
    val runeScores = mutableListOf<Triple<String, Recipe, Double>>() // (符文, 菜谱, 评分)
    
    selectedRunes.forEach { rune ->
        val runeRecipes = recipesByRune[rune] ?: emptyList()
        if (runeRecipes.isEmpty()) {
            System.out.println("符文 $rune 没有可用菜谱，跳过")
            return@forEach
        }
        
        // 计算该符文所有菜谱在每个厨师中的最高评分
        var bestRecipe: Recipe? = null
        var bestScore = 0.0
        var bestChefIndex = -1
        
        System.out.println("符文 $rune 菜谱评分详情:")
        
        runeRecipes.forEach { recipe ->
            // 检查该菜谱是否已被分配
            if (allocatedRecipes.any { it.recipe.name == recipe.name }) {
                return@forEach
            }
            
            // 计算该菜谱在每个厨师中的评分，找出最高分
            var recipeBestScore = 0.0
            var recipeBestChefIndex = -1
            var hasValidQuality = false // 标记是否有有效品级的菜谱
            
            enhancedChefs.forEachIndexed { chefIndex, enhancedChef ->
                // 检查该厨师是否已达到3道菜谱限制
                val chefCurrentRecipes = allocatedRecipes.count { it.assignedChef.chefId == bestChefGroup.chefGroup[chefIndex].chefId }
                if (chefCurrentRecipes >= 3) {
                    return@forEachIndexed
                }
                
                // 计算品级
                val quality = calculateRecipeQuality(enhancedChef, recipe)
                
                // 如果品级是"无法制作"，跳过这个厨师
                if (quality == "无法制作") {
                    return@forEachIndexed
                }
                
                // 检查厨师是否有"每制作一种神级料理贵客赠礼翻倍概率+*%"技能
                val chef = bestChefGroup.chefGroup[chefIndex]
                val hasDivineSkill = hasDivineRecipeSkill(chef, skills)
                
                // 如果有神级料理技能，检查菜谱品级是否满足要求
                if (hasDivineSkill) {
                    val isDivineOrHigher = quality == "神" || quality == "传"
                    if (!isDivineOrHigher) {
                        System.out.println("    厨师 ${chef.name} 有神级料理技能，但菜谱 ${recipe.name} 品级为 $quality，不满足神级要求，跳过")
                        return@forEachIndexed
                    }
                    System.out.println("    厨师 ${chef.name} 有神级料理技能，菜谱 ${recipe.name} 品级为 $quality，满足神级要求")
                }
                
                // 标记找到了有效品级的菜谱
                hasValidQuality = true
                
                val qualityScore = when (quality) {
                    "传" -> 100000.0
                    "神" -> 100000.0
                    "特" -> 100000.0
                    "优" -> 10000.0
                    "可" -> 1000.0
                    "无法制作" -> -100000.0
                    else -> 0.0
                }
                
                // 时间分数：每秒减去1分，时间越长扣分越多
                // 计算评分时，双贵客菜谱时间除2
                val guestCount = gameData?.guests?.count { guest ->
                    guest.gifts.any { gift -> 
                        gift.recipe == recipe.name 
                    }
                } ?: 1
                val adjustedTime = if (guestCount >= 2) recipe.time / 2 else recipe.time
                val timeScore = -adjustedTime
                val totalScore = qualityScore + timeScore
                
                if (totalScore > recipeBestScore) {
                    recipeBestScore = totalScore
                    recipeBestChefIndex = chefIndex
                }
            }
            
            // 打印该菜谱的评分详情
            if (recipeBestChefIndex >= 0) {
                val bestChef = bestChefGroup.chefGroup[recipeBestChefIndex]
                val quality = calculateRecipeQuality(enhancedChefs[recipeBestChefIndex], recipe)
                val qualityScore = when (quality) {
                    "传" -> 100000.0
                    "神" -> 100000.0
                    "特" -> 100000.0
                    "优" -> 10000.0
                    "可" -> 1000.0
                    "无法制作" -> -100000.0
                    else -> 0.0
                }
                val guestCount = gameData?.guests?.count { guest ->
                    guest.gifts.any { gift -> 
                        gift.recipe == recipe.name 
                    }
                } ?: 1
                val adjustedTime = if (guestCount >= 2) recipe.time / 2 else recipe.time
                val timeScore = -adjustedTime
                val totalScore = qualityScore + timeScore
                val timeFormatted = formatTime(recipe.time)
                val guestInfo = if (guestCount >= 2) " (${guestCount}贵客,评分时间${adjustedTime}秒)" else ""
                System.out.println("  ${recipe.name} - 最佳厨师: ${bestChef.name}, 品级:$quality(${String.format("%.0f", qualityScore)}分), 时间:${recipe.time}秒${timeFormatted}(-${adjustedTime}分)$guestInfo, 总分:${String.format("%.0f", totalScore)}")
            }
            
            // 更新该符文的最佳菜谱 - 只有当有有效品级时才更新
            if (hasValidQuality && recipeBestScore > bestScore) {
                bestScore = recipeBestScore
                bestRecipe = recipe
                bestChefIndex = recipeBestChefIndex
            }
        }
        
        if (bestRecipe != null && bestChefIndex >= 0) {
            val bestChef = bestChefGroup.chefGroup[bestChefIndex]
            runeScores.add(Triple(rune, bestRecipe, bestScore))
            System.out.println("符文 $rune 最高评分菜谱: ${bestRecipe.name} (最佳厨师: ${bestChef.name}, 评分: ${String.format("%.0f", bestScore)})")
        }
    }
    
    // 按评分降序排序符文，优先分配评分最高的
    runeScores.sortByDescending { it.third }
    
    System.out.println("=== 第一轮符文评分排序 ===")
    runeScores.forEachIndexed { index, (rune, recipe, score) ->
        System.out.println("  ${index + 1}. 符文: $rune, 菜谱: ${recipe.name}, 评分: ${String.format("%.0f", score)}")
    }
    
    // 按评分顺序分配菜谱
    for ((rune, bestRecipe, bestScore) in runeScores) {
        if (shouldStopFirstRound) {
            System.out.println("第一轮时间已达标，跳过剩余符文分配")
            break
        }
        
        System.out.println("=== 开始分配符文: $rune (评分: ${String.format("%.0f", bestScore)}) ===")
        
        // 找到制作该菜谱的最佳厨师（计算每个厨师制作该菜谱的分数）
        var bestChefIndex = -1
        var bestChefRecipeScore = 0.0
        var bestQuality = ""
        
        System.out.println("计算每个厨师制作该菜谱的分数:")
        
        enhancedChefs.forEachIndexed { chefIndex, enhancedChef ->
            // 检查该厨师是否已达到3道菜谱限制
            val chefCurrentRecipes = allocatedRecipes.count { it.assignedChef.chefId == bestChefGroup.chefGroup[chefIndex].chefId }
            if (chefCurrentRecipes >= 3) {
                System.out.println("  厨师${chefIndex + 1}: ${bestChefGroup.chefGroup[chefIndex].name} - 已达到3道菜谱限制，跳过")
                return@forEachIndexed
            }
            
            // 计算该厨师制作当前菜谱的分数
            val chefName = bestChefGroup.chefGroup[chefIndex].name
            
            System.out.println("  厨师${chefIndex + 1}: $chefName 制作 ${bestRecipe.name} 的分数计算:")
            
            // 检查厨师是否有"每制作一种神级料理贵客赠礼翻倍概率+*%"技能
            val hasDivineSkill = hasDivineRecipeSkill(bestChefGroup.chefGroup[chefIndex], skills)
            
            // 计算品级
            val quality = calculateRecipeQuality(enhancedChef, bestRecipe)
            
            // 如果有神级料理技能，检查菜谱品级是否满足要求
            if (hasDivineSkill) {
                val isDivineOrHigher = quality == "神" || quality == "传"
                if (!isDivineOrHigher) {
                    System.out.println("  厨师${chefIndex + 1}: $chefName 有神级料理技能，但菜谱 ${bestRecipe.name} 品级为 $quality，不满足神级要求，跳过")
                    return@forEachIndexed
                }
                System.out.println("  厨师${chefIndex + 1}: $chefName 有神级料理技能，菜谱 ${bestRecipe.name} 品级为 $quality，满足神级要求")
            }
            
            val qualityScore = when (quality) {
                "传" -> 100000.0
                "神" -> 100000.0
                "特" -> 100000.0
                "优" -> 10000.0
                "可" -> 1000.0
                "无法制作" -> -100000.0
                else -> 0.0
            }
            
            // 时间分数：每秒减去1分，时间越长扣分越多
            // 计算评分时，双贵客菜谱时间除2
            val guestCount = gameData?.guests?.count { guest ->
                guest.gifts.any { gift -> 
                    gift.recipe == bestRecipe.name 
                }
            } ?: 1
            val adjustedTime = if (guestCount >= 2) bestRecipe.time / 2 else bestRecipe.time
            val timeScore = -adjustedTime
            val totalScore = qualityScore + timeScore
            
            val timeFormatted = formatTime(bestRecipe.time)
            val guestInfo = if (guestCount >= 2) " (${guestCount}贵客,评分时间${adjustedTime}秒)" else ""
            System.out.println("    ${bestRecipe.name}: 品级:$quality(${String.format("%.0f", qualityScore)}分), 时间:${bestRecipe.time}秒${timeFormatted}(-${adjustedTime}分)$guestInfo, 总分:${String.format("%.0f", totalScore)}")
            
            // 选择制作该菜谱分数最高的厨师
            if (totalScore > bestChefRecipeScore) {
                bestChefRecipeScore = totalScore
                bestChefIndex = chefIndex
                bestQuality = quality
            }
        }
        
        if (bestChefIndex >= 0) {
            val bestOriginalChef = bestChefGroup.chefGroup[bestChefIndex]
            System.out.println("选择厨师: ${bestOriginalChef.name} (制作该菜谱分数: ${String.format("%.0f", bestChefRecipeScore)})")
            
            // 在分配前再次检查菜谱品级，确保不是"无法制作"
            val finalQuality = calculateRecipeQuality(enhancedChefs[bestChefIndex], bestRecipe)
            if (finalQuality == "无法制作") {
                System.out.println("⚠️ 跳过无法制作的菜谱: ${bestRecipe.name}")
                continue
            }
            
            // 检查有神级料理技能的厨师是否被分配了满足要求的菜谱
            val hasDivineSkill = hasDivineRecipeSkill(bestOriginalChef, skills)
            if (hasDivineSkill) {
                val isDivineOrHigher = finalQuality == "神" || finalQuality == "传"
                if (!isDivineOrHigher) {
                    System.out.println("⚠️ 厨师 ${bestOriginalChef.name} 有神级料理技能，但菜谱 ${bestRecipe.name} 最终品级为 $finalQuality，不满足神级要求")
                    System.out.println("重新评估其他厨师制作该符文菜谱的评分...")
                    
                    // 重新评估其他厨师的评分，排除当前选中的厨师
                    var alternativeBestChefIndex = -1
                    var alternativeBestScore = 0.0
                    var alternativeBestQuality = ""
                    
                    enhancedChefs.forEachIndexed { chefIndex, enhancedChef ->
                        // 跳过当前选中的厨师
                        if (chefIndex == bestChefIndex) {
                            return@forEachIndexed
                        }
                        
                        // 检查该厨师是否已达到3道菜谱限制
                        val chefCurrentRecipes = allocatedRecipes.count { it.assignedChef.chefId == bestChefGroup.chefGroup[chefIndex].chefId }
                        if (chefCurrentRecipes >= 3) {
                            return@forEachIndexed
                        }
                        
                        val chefName = bestChefGroup.chefGroup[chefIndex].name
                        System.out.println("  重新评估厨师${chefIndex + 1}: $chefName 制作 ${bestRecipe.name} 的分数:")
                        
                        // 检查厨师是否有神级料理技能
                        val alternativeHasDivineSkill = hasDivineRecipeSkill(bestChefGroup.chefGroup[chefIndex], skills)
                        
                        // 计算品级
                        val quality = calculateRecipeQuality(enhancedChef, bestRecipe)
                        
                        // 如果有神级料理技能，检查菜谱品级是否满足要求
                        if (alternativeHasDivineSkill) {
                            val isDivineOrHigher = quality == "神" || quality == "传"
                            if (!isDivineOrHigher) {
                                System.out.println("    厨师 ${chefName} 有神级料理技能，但菜谱 ${bestRecipe.name} 品级为 $quality，不满足神级要求，跳过")
                                return@forEachIndexed
                            }
                            System.out.println("    厨师 ${chefName} 有神级料理技能，菜谱 ${bestRecipe.name} 品级为 $quality，满足神级要求")
                        }
                        
                        val qualityScore = when (quality) {
                            "传" -> 100000.0
                            "神" -> 100000.0
                            "特" -> 100000.0
                            "优" -> 10000.0
                            "可" -> 1000.0
                            "无法制作" -> -100000.0
                            else -> 0.0
                        }
                        
                        // 时间分数：每秒减去1分，时间越长扣分越多
                        val guestCount = gameData?.guests?.count { guest ->
                            guest.gifts.any { gift -> 
                                gift.recipe == bestRecipe.name 
                            }
                        } ?: 1
                        val adjustedTime = if (guestCount >= 2) bestRecipe.time / 2 else bestRecipe.time
                        val timeScore = -adjustedTime
                        val totalScore = qualityScore + timeScore
                        
                        val timeFormatted = formatTime(bestRecipe.time)
                        val guestInfo = if (guestCount >= 2) " (${guestCount}贵客,评分时间${adjustedTime}秒)" else ""
                        System.out.println("    ${bestRecipe.name}: 品级:$quality(${String.format("%.0f", qualityScore)}分), 时间:${bestRecipe.time}秒${timeFormatted}(-${adjustedTime}分)$guestInfo, 总分:${String.format("%.0f", totalScore)}")
                        
                        // 选择制作该菜谱分数最高的厨师
                        if (totalScore > alternativeBestScore) {
                            alternativeBestScore = totalScore
                            alternativeBestChefIndex = chefIndex
                            alternativeBestQuality = quality
                        }
                    }
                    
                    // 如果找到了替代厨师
                    if (alternativeBestChefIndex >= 0) {
                        val alternativeChef = bestChefGroup.chefGroup[alternativeBestChefIndex]
                        System.out.println("✓ 找到替代厨师: ${alternativeChef.name} (制作该菜谱分数: ${String.format("%.0f", alternativeBestScore)})")
                        
                        // 更新选中的厨师和相关信息
                        bestChefIndex = alternativeBestChefIndex
                        bestChefRecipeScore = alternativeBestScore
                        bestQuality = alternativeBestQuality
                        
                        // 重新计算最终品级
                        val finalQualityAlternative = calculateRecipeQuality(enhancedChefs[bestChefIndex], bestRecipe)
                        if (finalQualityAlternative == "无法制作") {
                            System.out.println("⚠️ 替代厨师也无法制作该菜谱，跳过")
                            continue
                        }
                        
                        System.out.println("✓ 使用替代厨师 ${alternativeChef.name} 分配菜谱 ${bestRecipe.name} (品级:$finalQualityAlternative)")
                        
                        // 更新最终品级，用于后续分配
                        val finalQualityForAllocation = finalQualityAlternative
                    } else {
                        System.out.println("⚠️ 没有找到合适的替代厨师，需要重新评估该符文下的所有菜谱")
                        
                        // 重新评估该符文下的所有菜谱，找出评分最高的菜谱和厨师组合
                        var bestAlternativeRecipe: Recipe? = null
                        var bestAlternativeChefIndex = -1
                        var bestAlternativeScore = 0.0
                        var bestAlternativeQuality = ""
                        var bestRecipe = bestRecipe // 临时变量，用于重新分配
                        
                        System.out.println("重新评估符文 $rune 下的所有菜谱...")
                        
                        val runeRecipes = recipesByRune[rune] ?: emptyList()
                        runeRecipes.forEach { recipe ->
                            enhancedChefs.forEachIndexed { chefIndex, enhancedChef ->
                                // 检查该厨师是否已达到3道菜谱限制
                                val chefCurrentRecipes = allocatedRecipes.count { it.assignedChef.chefId == bestChefGroup.chefGroup[chefIndex].chefId }
                                if (chefCurrentRecipes >= 3) {
                                    return@forEachIndexed
                                }
                                
                                // 检查该菜谱是否已被分配
                                if (allocatedRecipes.any { it.recipe.name == recipe.name }) {
                                    return@forEachIndexed
                                }
                                
                                val chefName = bestChefGroup.chefGroup[chefIndex].name
                                
                                // 检查厨师是否有神级料理技能
                                val alternativeHasDivineSkill = hasDivineRecipeSkill(bestChefGroup.chefGroup[chefIndex], skills)
                                
                                // 计算品级
                                val quality = calculateRecipeQuality(enhancedChef, recipe)
                                
                                // 如果有神级料理技能，检查菜谱品级是否满足要求
                                if (alternativeHasDivineSkill) {
                                    val isDivineOrHigher = quality == "神" || quality == "传"
                                    if (!isDivineOrHigher) {
                                        return@forEachIndexed
                                    }
                                }
                                
                                val qualityScore = when (quality) {
                                    "传" -> 100000.0
                                    "神" -> 100000.0
                                    "特" -> 100000.0
                                    "优" -> 10000.0
                                    "可" -> 1000.0
                                    "无法制作" -> -100000.0
                                    else -> 0.0
                                }
                                
                                // 时间分数：每秒减去1分，时间越长扣分越多
                                val guestCount = gameData?.guests?.count { guest ->
                                    guest.gifts.any { gift -> 
                                        gift.recipe == recipe.name 
                                    }
                                } ?: 1
                                val adjustedTime = if (guestCount >= 2) recipe.time / 2 else recipe.time
                                val timeScore = -adjustedTime
                                val totalScore = qualityScore + timeScore
                                
                                val timeFormatted = formatTime(recipe.time)
                                val guestInfo = if (guestCount >= 2) " (${guestCount}贵客,评分时间${adjustedTime}秒)" else ""
                                System.out.println("    重新评估: 厨师 $chefName -> ${recipe.name}: 品级:$quality(${String.format("%.0f", qualityScore)}分), 时间:${recipe.time}秒${timeFormatted}(-${adjustedTime}分)$guestInfo, 总分:${String.format("%.0f", totalScore)}")
                                
                                // 选择评分最高的菜谱和厨师组合
                                if (totalScore > bestAlternativeScore) {
                                    bestAlternativeScore = totalScore
                                    bestAlternativeRecipe = recipe
                                    bestAlternativeChefIndex = chefIndex
                                    bestAlternativeQuality = quality
                                }
                            }
                        }
                        
                        // 如果找到了替代菜谱和厨师
                        if (bestAlternativeRecipe != null && bestAlternativeChefIndex >= 0) {
                            val alternativeChef = bestChefGroup.chefGroup[bestAlternativeChefIndex]
                            System.out.println("✓ 找到最佳替代方案: 厨师 ${alternativeChef.name} -> 菜谱 ${bestAlternativeRecipe.name} (品级:$bestAlternativeQuality, 评分:${String.format("%.0f", bestAlternativeScore)})")
                            
                            // 更新选中的菜谱、厨师和相关信息
                            bestRecipe = bestAlternativeRecipe
                            bestChefIndex = bestAlternativeChefIndex
                            bestChefRecipeScore = bestAlternativeScore
                            bestQuality = bestAlternativeQuality
                            
                            // 重新计算最终品级
                            val finalQualityAlternative = calculateRecipeQuality(enhancedChefs[bestChefIndex], bestRecipe)
                            if (finalQualityAlternative == "无法制作") {
                                System.out.println("⚠️ 替代方案也无法制作，跳过该符文")
                                continue
                            }
                            
                            System.out.println("✓ 使用替代方案: 厨师 ${alternativeChef.name} -> 菜谱 ${bestRecipe.name} (品级:$finalQualityAlternative)")
                            
                            // 更新最终品级
                            val finalQualityForAllocation = finalQualityAlternative
                        } else {
                            System.out.println("⚠️ 没有找到任何合适的替代方案，跳过该符文")
                            continue
                        }
                    }
                } else {
                    System.out.println("✓ 厨师 ${bestOriginalChef.name} 有神级料理技能，菜谱 ${bestRecipe.name} 最终品级为 $finalQuality，满足神级要求")
                }
            }
            
            // 分配菜谱
            val quantity = calculateRecipeQuantity(bestRecipe, bestChefGroup.totalGuestRate, settingsStorage, false, recipeLimits)
            val cookingTime = calculateCookingTime(bestRecipe.time, quantity, bestChefGroup.totalTimeBonus)
            
            // 确定最终使用的品级
            val finalQualityForAllocation = if (hasDivineSkill && bestChefIndex != -1) {
                // 如果使用了替代厨师，使用替代厨师的品级
                calculateRecipeQuality(enhancedChefs[bestChefIndex], bestRecipe)
            } else {
                finalQuality
            }
            
            val allocatedRecipe = AllocatedRecipe(
                recipe = bestRecipe,
                assignedChef = bestChefGroup.chefGroup[bestChefIndex],
                rune = rune,
                quantity = quantity,
                cookingTime = cookingTime,
                quality = finalQualityForAllocation,
                isSupplemented = false
            )
            
            allocatedRecipes.add(allocatedRecipe)
            totalCookingTime += cookingTime
            
            System.out.println("  ✓ 成功分配: 厨师 ${bestChefGroup.chefGroup[bestChefIndex].name} -> ${bestRecipe.name} (品级:$finalQualityForAllocation, 份数:$quantity, 时间:${cookingTime}秒)")
            
            // 检查是否已经达标
            if (totalCookingTime >= timeLimitSeconds) {
                System.out.println("✓ 第一轮分配后时间限制达标（超过${timeLimitHours}小时），立即停止分配")
                shouldStopFirstRound = true
                break
            }
        } else {
            System.out.println("符文 $rune 无法分配菜谱（所有厨师都已达到3道菜谱限制）")
        }
        
        System.out.println("")
    }
    
    // 第一轮分配已完成，现在检查是否需要后续轮次分配
    
    // 检查总制作时间是否达标
    
    System.out.println("=== 分配结果总结 ===")
    System.out.println("总制作时间: ${totalCookingTime}秒 (${String.format("%.1f", totalCookingTime / 3600.0)}小时)")
    System.out.println("时间限制: ${timeLimitSeconds}秒 (${timeLimitHours}小时)")
    
    if (totalCookingTime >= timeLimitSeconds) {
        System.out.println("✓ 时间限制达标（超过${timeLimitHours}小时）")
        
        // 在时间达标后，为有神级料理技能的厨师补充菜谱
        System.out.println("=== 检查神级料理技能厨师菜谱补充 ===")
        System.out.println("检查厨师组: ${bestChefGroup.chefGroup.map { "${it.name}(${if (it.got) "已拥有" else "未拥有"})" }}")
        System.out.println("当前已分配菜谱数量: ${allocatedRecipes.size}")
        
        // 强制检查所有厨师，不管是否参与了主分配
        val supplementedRecipes = supplementDivineSkillChefRecipes(allocatedRecipes, bestChefGroup.chefGroup, enhancedChefs, skills, gameData)
        if (supplementedRecipes.isNotEmpty()) {
            System.out.println("✓ 成功补充 ${supplementedRecipes.size} 道强补菜谱")
            supplementedRecipes.forEach { recipe ->
                System.out.println("  - 强补菜谱: ${recipe.recipe.name} -> 厨师 ${recipe.assignedChef.name} (品级:${recipe.quality}, 份数:${recipe.quantity})")
            }
            // 将补充的菜谱添加到总分配结果中
            allocatedRecipes.addAll(supplementedRecipes)
            System.out.println("补充后总菜谱数量: ${allocatedRecipes.size}")
        } else {
            System.out.println("✓ 无需补充菜谱")
        }
        
        // 创建分配结果
        return RecipeAllocationResult(
            chefGroup = bestChefGroup.chefGroup,
            allocatedRecipes = allocatedRecipes,
            totalCookingTime = totalCookingTime,
            totalGuestRate = bestChefGroup.totalGuestRate,
            totalCritRate = bestChefGroup.totalCritRate,
            totalTimeBonus = bestChefGroup.totalTimeBonus,
            unitTime = bestChefGroup.unitTime,
            hundredPotOutput = bestChefGroup.hundredPotOutput,
            unitFood = bestChefGroup.unitFood,
            enhancedChefs = enhancedChefs
        )
    } else {
        System.out.println("✗ 时间限制未达标（未超过${timeLimitHours}小时），开始后续轮次分配")
        
        // 开始后续轮次分配，直到时间达标
        var round = 1
        var continueAllocation = true
        val maxRounds = 100 // 最大轮次限制，防止无限循环
        
        while (continueAllocation && totalCookingTime < timeLimitSeconds && round <= maxRounds) {
            System.out.println("=== 开始第${round + 1}轮分配 ===")
            
            // 第${round + 1}轮分配：按符文评分排序分配菜谱，确保所有符文都被分配
            var shouldStopRound = false
            
            // 计算每种符文的剩余菜谱最高评分
            val runeScores = mutableListOf<Triple<String, Recipe, Double>>() // (符文, 菜谱, 评分)
            
            selectedRunes.forEach { rune ->
                val runeRecipes = recipesByRune[rune] ?: emptyList()
                if (runeRecipes.isEmpty()) {
                    return@forEach
                }
                
                // 计算该符文剩余菜谱的最高评分
                var bestRecipe: Recipe? = null
                var bestScore = 0.0
                var bestChefIndex = -1
                
                System.out.println("第${round + 1}轮符文 $rune 剩余菜谱评分详情:")
                
                runeRecipes.forEach { recipe ->
                    // 检查该菜谱是否已被分配
                    if (!allocatedRecipes.any { it.recipe.name == recipe.name }) {
                        // 计算该菜谱在每个厨师中的评分，找出最高分
                        var recipeBestScore = 0.0
                        var recipeBestChefIndex = -1
                        var hasValidQuality = false // 标记是否有有效品级的菜谱
                        
                        enhancedChefs.forEachIndexed { chefIndex, enhancedChef ->
                            // 检查该厨师是否已达到3道菜谱限制
                            val chefCurrentRecipes = allocatedRecipes.count { it.assignedChef.chefId == bestChefGroup.chefGroup[chefIndex].chefId }
                            if (chefCurrentRecipes >= 3) {
                                return@forEachIndexed
                            }
                            
                            // 计算品级
                            val quality = calculateRecipeQuality(enhancedChef, recipe)
                            val qualityScore = when (quality) {
                                "传" -> 100000.0
                                "神" -> 100000.0
                                "特" -> 100000.0
                                "优" -> 10000.0
                                "可" -> 1000.0
                                "无法制作" -> -100000.0
                                else -> 0.0
                            }
                            
                            // 如果品级是"无法制作"，跳过这个厨师
                            if (quality == "无法制作") {
                                return@forEachIndexed
                            }
                            
                            // 标记找到了有效品级的菜谱
                            hasValidQuality = true
                            
                            // 时间分数：每秒减去1分，时间越长扣分越多
                            // 计算评分时，双贵客菜谱时间除2
                            val guestCount = gameData?.guests?.count { guest ->
                                guest.gifts.any { gift -> 
                                    gift.recipe == recipe.name 
                                }
                            } ?: 1
                            val adjustedTime = if (guestCount >= 2) recipe.time / 2 else recipe.time
                            val timeScore = -adjustedTime
                            val totalScore = qualityScore + timeScore
                            
                            if (totalScore > recipeBestScore) {
                                recipeBestScore = totalScore
                                recipeBestChefIndex = chefIndex
                            }
                        }
                        
                        // 打印该菜谱的评分详情
                        if (recipeBestChefIndex >= 0) {
                            val bestChef = bestChefGroup.chefGroup[recipeBestChefIndex]
                            val quality = calculateRecipeQuality(enhancedChefs[recipeBestChefIndex], recipe)
                            val qualityScore = when (quality) {
                                "传" -> 100000.0
                                "神" -> 100000.0
                                "特" -> 100000.0
                                "优" -> 10000.0
                                "可" -> 1000.0
                                "无法制作" -> -100000.0
                                else -> 0.0
                            }
                            val guestCount = gameData?.guests?.count { guest ->
                                guest.gifts.any { gift -> 
                                    gift.recipe == recipe.name 
                                }
                            } ?: 1
                            val adjustedTime = if (guestCount >= 2) recipe.time / 2 else recipe.time
                            val timeScore = -adjustedTime
                            val totalScore = qualityScore + timeScore
                            val timeFormatted = formatTime(recipe.time)
                            val guestInfo = if (guestCount >= 2) " (${guestCount}贵客,评分时间${adjustedTime}秒)" else ""
                            System.out.println("  ${recipe.name} - 最佳厨师: ${bestChef.name}, 品级:$quality(${String.format("%.0f", qualityScore)}分), 时间:${recipe.time}秒${timeFormatted}(-${adjustedTime}分)$guestInfo, 总分:${String.format("%.0f", totalScore)}")
                        }
                        
                        // 更新该符文的最佳菜谱 - 只有当有有效品级时才更新
                        if (hasValidQuality && recipeBestScore > bestScore) {
                            bestScore = recipeBestScore
                            bestRecipe = recipe
                            bestChefIndex = recipeBestChefIndex
                        }
                    }
                }
                
                if (bestRecipe != null && bestChefIndex >= 0) {
                    val bestChef = bestChefGroup.chefGroup[bestChefIndex]
                    runeScores.add(Triple(rune, bestRecipe, bestScore))
                    System.out.println("第${round + 1}轮符文 $rune 最高评分菜谱: ${bestRecipe.name} (最佳厨师: ${bestChef.name}, 评分: ${String.format("%.0f", bestScore)})")
                }
            }
            
            // 按评分降序排序符文，优先分配评分最高的
            runeScores.sortByDescending { it.third }
            
            System.out.println("=== 第${round + 1}轮符文评分排序 ===")
            runeScores.forEachIndexed { index, (rune, recipe, score) ->
                System.out.println("  ${index + 1}. 符文: $rune, 菜谱: ${recipe.name}, 评分: ${String.format("%.0f", score)}")
            }
            
            // 按评分顺序分配菜谱
            for ((rune, bestRecipe, bestScore) in runeScores) {
                if (shouldStopRound) {
                    System.out.println("第${round + 1}轮时间已达标，跳过剩余符文分配")
                    break
                }
                
                System.out.println("=== 第${round + 1}轮开始分配符文: $rune (评分: ${String.format("%.0f", bestScore)}) ===")
                
                // 找到制作该菜谱的最佳厨师
                // 注意：这里应该使用bestRecipe（从符文评分中选出的最佳菜谱），而不是重新计算
                var bestChefIndex = -1
                var bestQuality = ""
                
                // 用于存储替代方案的信息
                var alternativeRecipe: Recipe? = null
                var alternativeChefIndex = -1
                
                // 直接使用符文评分中选出的最佳菜谱和厨师
                // 从符文评分中获取该符文的最佳菜谱和厨师信息
                val runeScoreInfo = runeScores.find { it.first == rune }
                if (runeScoreInfo != null) {
                    val (_, recipe, score) = runeScoreInfo
                    // 找到制作该菜谱的最佳厨师
                    var bestChefIndexForRecipe = -1
                    var bestChefScoreForRecipe = 0.0
                    
                    enhancedChefs.forEachIndexed { chefIndex, enhancedChef ->
                        // 检查该厨师是否已达到3道菜谱限制
                        val chefCurrentRecipes = allocatedRecipes.count { it.assignedChef.chefId == bestChefGroup.chefGroup[chefIndex].chefId }
                        if (chefCurrentRecipes >= 3) {
                            return@forEachIndexed
                        }
                        
                        // 计算该厨师制作该菜谱的评分
                        val quality = calculateRecipeQuality(enhancedChef, recipe)
                        
                        // 如果品级是"无法制作"，跳过这个厨师
                        if (quality == "无法制作") {
                            return@forEachIndexed
                        }
                        
                        val qualityScore = when (quality) {
                            "传" -> 100000.0
                            "神" -> 100000.0
                            "特" -> 100000.0
                            "优" -> 10000.0
                            "可" -> 1000.0
                            "无法制作" -> -100000.0
                            else -> 0.0
                        }
                        
                        // 时间分数：每秒减去1分，时间越长扣分越多
                        val timeScore = -recipe.time
                        val totalScore = qualityScore + timeScore
                        
                        if (totalScore > bestChefScoreForRecipe) {
                            bestChefScoreForRecipe = totalScore
                            bestChefIndexForRecipe = chefIndex
                            bestQuality = quality
                        }
                    }
                    
                    bestChefIndex = bestChefIndexForRecipe
                    
                    System.out.println("第${round + 1}轮使用符文评分中选出的最佳菜谱: ${recipe.name} (评分: ${String.format("%.0f", score)})")
                    System.out.println("第${round + 1}轮选择厨师: ${if (bestChefIndex >= 0) bestChefGroup.chefGroup[bestChefIndex].name else "无"} (菜谱评分: ${String.format("%.0f", bestChefScoreForRecipe)})")
                }
                
                if (bestChefIndex >= 0) {
                    val bestOriginalChef = bestChefGroup.chefGroup[bestChefIndex]
                    
                    // 分配菜谱 - 使用符文评分中选出的最佳菜谱
                    val runeScoreInfo = runeScores.find { it.first == rune }
                    if (runeScoreInfo != null) {
                        val (_, recipe, score) = runeScoreInfo
                        
                        // 在分配前再次检查菜谱品级，确保不是"无法制作"
                        val finalQuality = calculateRecipeQuality(enhancedChefs[bestChefIndex], recipe)
                        if (finalQuality == "无法制作") {
                            System.out.println("⚠️ 跳过无法制作的菜谱: ${recipe.name}")
                            continue
                        }
                        
                        // 检查有神级料理技能的厨师是否被分配了满足要求的菜谱
                        val hasDivineSkill = hasDivineRecipeSkill(bestOriginalChef, skills)
                        if (hasDivineSkill) {
                            val isDivineOrHigher = finalQuality == "神" || finalQuality == "传"
                            if (!isDivineOrHigher) {
                                System.out.println("⚠️ 第${round + 1}轮: 厨师 ${bestOriginalChef.name} 有神级料理技能，但菜谱 ${recipe.name} 最终品级为 $finalQuality，不满足神级要求")
                                System.out.println("重新评估其他厨师制作该符文菜谱的评分...")
                                
                                // 重新评估其他厨师的评分，排除当前选中的厨师
                                var alternativeBestChefIndex = -1
                                var alternativeBestScore = 0.0
                                var alternativeBestQuality = ""
                                
                                enhancedChefs.forEachIndexed { chefIndex, enhancedChef ->
                                    // 跳过当前选中的厨师
                                    if (chefIndex == bestChefIndex) {
                                        return@forEachIndexed
                                    }
                                    
                                    // 检查该厨师是否已达到3道菜谱限制
                                    val chefCurrentRecipes = allocatedRecipes.count { it.assignedChef.chefId == bestChefGroup.chefGroup[chefIndex].chefId }
                                    if (chefCurrentRecipes >= 3) {
                                        return@forEachIndexed
                                    }
                                    
                                    val chefName = bestChefGroup.chefGroup[chefIndex].name
                                    System.out.println("  重新评估厨师${chefIndex + 1}: $chefName 制作 ${recipe.name} 的分数:")
                                    
                                    // 检查厨师是否有神级料理技能
                                    val alternativeHasDivineSkill = hasDivineRecipeSkill(bestChefGroup.chefGroup[chefIndex], skills)
                                    
                                    // 计算品级
                                    val quality = calculateRecipeQuality(enhancedChef, recipe)
                                    
                                    // 如果有神级料理技能，检查菜谱品级是否满足要求
                                    if (alternativeHasDivineSkill) {
                                        val isDivineOrHigher = quality == "神" || quality == "传"
                                        if (!isDivineOrHigher) {
                                            System.out.println("    厨师 ${chefName} 有神级料理技能，但菜谱 ${recipe.name} 品级为 $quality，不满足神级要求，跳过")
                                            return@forEachIndexed
                                        }
                                        System.out.println("    厨师 ${chefName} 有神级料理技能，菜谱 ${recipe.name} 品级为 $quality，满足神级要求")
                                    }
                                    
                                    val qualityScore = when (quality) {
                                        "传" -> 100000.0
                                        "神" -> 100000.0
                                        "特" -> 100000.0
                                        "优" -> 10000.0
                                        "可" -> 1000.0
                                        "无法制作" -> -100000.0
                                        else -> 0.0
                                    }
                                    
                                    // 时间分数：每秒减去1分，时间越长扣分越多
                                    val timeScore = -recipe.time
                                    val totalScore = qualityScore + timeScore
                                    
                                    System.out.println("    ${recipe.name}: 品级:$quality(${String.format("%.0f", qualityScore)}分), 时间:${recipe.time}秒(-${recipe.time}分), 总分:${String.format("%.0f", totalScore)}")
                                    
                                    // 选择制作该菜谱分数最高的厨师
                                    if (totalScore > alternativeBestScore) {
                                        alternativeBestScore = totalScore
                                        alternativeBestChefIndex = chefIndex
                                        alternativeBestQuality = quality
                                    }
                                }
                                
                                // 如果找到了替代厨师
                                if (alternativeBestChefIndex >= 0) {
                                    val alternativeChef = bestChefGroup.chefGroup[alternativeBestChefIndex]
                                    System.out.println("✓ 第${round + 1}轮: 找到替代厨师: ${alternativeChef.name} (制作该菜谱分数: ${String.format("%.0f", alternativeBestScore)})")
                                    
                                    // 更新选中的厨师和相关信息
                                    bestChefIndex = alternativeBestChefIndex
                                    
                                    // 重新计算最终品级
                                    val finalQualityAlternative = calculateRecipeQuality(enhancedChefs[bestChefIndex], recipe)
                                    if (finalQualityAlternative == "无法制作") {
                                        System.out.println("⚠️ 第${round + 1}轮: 替代厨师也无法制作该菜谱，跳过")
                                        continue
                                    }
                                    
                                    System.out.println("✓ 第${round + 1}轮: 使用替代厨师 ${alternativeChef.name} 分配菜谱 ${recipe.name} (品级:$finalQualityAlternative)")
                                    
                                    // 更新最终品级
                                    val finalQualityForAllocation = finalQualityAlternative
                                } else {
                                    System.out.println("⚠️ 第${round + 1}轮: 没有找到合适的替代厨师，需要重新评估该符文下的所有菜谱")
                                    
                                    // 重新评估该符文下的所有菜谱，找出评分最高的菜谱和厨师组合
                                    var bestAlternativeRecipe: Recipe? = null
                                    var bestAlternativeChefIndex = -1
                                    var bestAlternativeScore = 0.0
                                    var bestAlternativeQuality = ""
                                    var bestRecipe = bestRecipe // 临时变量，用于重新分配
                                    
                                    System.out.println("第${round + 1}轮重新评估符文 $rune 下的所有菜谱...")
                                    
                                    val runeRecipes = recipesByRune[rune] ?: emptyList()
                                    runeRecipes.forEach { recipe ->
                                        enhancedChefs.forEachIndexed { chefIndex, enhancedChef ->
                                            // 检查该厨师是否已达到3道菜谱限制
                                            val chefCurrentRecipes = allocatedRecipes.count { it.assignedChef.chefId == bestChefGroup.chefGroup[chefIndex].chefId }
                                            if (chefCurrentRecipes >= 3) {
                                                return@forEachIndexed
                                            }
                                            
                                            // 检查该菜谱是否已被分配
                                            if (allocatedRecipes.any { it.recipe.name == recipe.name }) {
                                                return@forEachIndexed
                                            }
                                            
                                            val chefName = bestChefGroup.chefGroup[chefIndex].name
                                            
                                            // 检查厨师是否有神级料理技能
                                            val alternativeHasDivineSkill = hasDivineRecipeSkill(bestChefGroup.chefGroup[chefIndex], skills)
                                            
                                            // 计算品级
                                            val quality = calculateRecipeQuality(enhancedChef, recipe)
                                            
                                            // 如果有神级料理技能，检查菜谱品级是否满足要求
                                            if (alternativeHasDivineSkill) {
                                                val isDivineOrHigher = quality == "神" || quality == "传"
                                                if (!isDivineOrHigher) {
                                                    return@forEachIndexed
                                                }
                                            }
                                            
                                            val qualityScore = when (quality) {
                                                "传" -> 100000.0
                                                "神" -> 100000.0
                                                "特" -> 100000.0
                                                "优" -> 10000.0
                                                "可" -> 1000.0
                                                "无法制作" -> -100000.0
                                                else -> 0.0
                                            }
                                            
                                            // 时间分数：每秒减去1分，时间越长扣分越多
                                            val timeScore = -recipe.time
                                            val totalScore = qualityScore + timeScore
                                            
                                            System.out.println("    第${round + 1}轮重新评估: 厨师 $chefName -> ${recipe.name}: 品级:$quality(${String.format("%.0f", qualityScore)}分), 时间:${recipe.time}秒(-${recipe.time}分), 总分:${String.format("%.0f", totalScore)}")
                                            
                                            // 选择评分最高的菜谱和厨师组合
                                            if (totalScore > bestAlternativeScore) {
                                                bestAlternativeScore = totalScore
                                                bestAlternativeRecipe = recipe
                                                bestAlternativeChefIndex = chefIndex
                                                bestAlternativeQuality = quality
                                            }
                                        }
                                    }
                                    
                                    // 如果找到了替代菜谱和厨师
                                    if (bestAlternativeRecipe != null && bestAlternativeChefIndex >= 0) {
                                        val alternativeChef = bestChefGroup.chefGroup[bestAlternativeChefIndex]
                                        System.out.println("✓ 第${round + 1}轮: 找到最佳替代方案: 厨师 ${alternativeChef.name} -> 菜谱 ${bestAlternativeRecipe.name} (品级:$bestAlternativeQuality, 评分:${String.format("%.0f", bestAlternativeScore)})")
                                        
                                        // 更新选中的菜谱、厨师和相关信息
                                        bestRecipe = bestAlternativeRecipe
                                        bestChefIndex = bestAlternativeChefIndex
                                        
                                        // 重新计算最终品级
                                        val finalQualityAlternative = calculateRecipeQuality(enhancedChefs[bestChefIndex], bestRecipe)
                                        if (finalQualityAlternative == "无法制作") {
                                            System.out.println("⚠️ 第${round + 1}轮: 替代方案也无法制作，跳过该符文")
                                            continue
                                        }
                                        
                                        System.out.println("✓ 第${round + 1}轮: 使用替代方案: 厨师 ${alternativeChef.name} -> 菜谱 ${bestRecipe.name} (品级:$finalQualityAlternative)")
                                        
                                        // 更新最终品级
                                        val finalQualityForAllocation = finalQualityAlternative
                                        
                                        // 重要：将替代方案信息存储到外层作用域，供后续分配逻辑使用
                                        alternativeRecipe = bestAlternativeRecipe
                                        alternativeChefIndex = bestAlternativeChefIndex
                                    } else {
                                        System.out.println("⚠️ 第${round + 1}轮: 没有找到任何合适的替代方案，跳过该符文")
                                        continue
                                    }
                                }
                            } else {
                                System.out.println("✓ 第${round + 1}轮: 厨师 ${bestOriginalChef.name} 有神级料理技能，菜谱 ${recipe.name} 最终品级为 $finalQuality，满足神级要求")
                            }
                        }
                        
                        // 确定最终使用的品级和菜谱
                        // 在后续轮次分配中，如果找到了替代方案，使用替代菜谱；否则使用原始菜谱
                        val finalRecipe = if (alternativeRecipe != null && alternativeChefIndex >= 0) {
                            // 如果找到了替代方案，使用替代菜谱
                            alternativeRecipe!!
                        } else {
                            // 否则使用原始菜谱
                            recipe
                        }
                        
                        val finalQualityForAllocation = if (hasDivineSkill && bestChefIndex != -1) {
                            // 如果使用了替代厨师，使用替代厨师的品级
                            calculateRecipeQuality(enhancedChefs[bestChefIndex], finalRecipe)
                        } else {
                            finalQuality
                        }
                        
                        val quantity = calculateRecipeQuantity(finalRecipe, bestChefGroup.totalGuestRate, settingsStorage, false, recipeLimits)
                        val cookingTime = calculateCookingTime(finalRecipe.time, quantity, bestChefGroup.totalTimeBonus)
                        
                        val allocatedRecipe = AllocatedRecipe(
                            recipe = finalRecipe,
                            assignedChef = bestChefGroup.chefGroup[bestChefIndex],
                            rune = rune,
                            quantity = quantity,
                            cookingTime = cookingTime,
                            quality = finalQualityForAllocation,
                            isSupplemented = false
                        )
                        
                        allocatedRecipes.add(allocatedRecipe)
                        totalCookingTime += cookingTime
                        
                        val singleTimeFormatted = formatTime(finalRecipe.time)
                        val cookingTimeFormatted = formatTime(cookingTime)
                        val totalTimeFormatted = formatTime(totalCookingTime)
                        System.out.println("  ✓ 第${round + 1}轮成功分配: 厨师 ${bestChefGroup.chefGroup[bestChefIndex].name} -> ${finalRecipe.name} (品级:$finalQualityForAllocation, 份数:$quantity, 单份时间:${finalRecipe.time}秒${singleTimeFormatted}, 总份数时间:${cookingTime}秒${cookingTimeFormatted})")
                        System.out.println("  当前总制作时间: ${totalCookingTime}秒${totalTimeFormatted} (${String.format("%.1f", totalCookingTime / 3600.0)}小时)")
                        
                        // 检查是否已经达标
                        if (totalCookingTime >= timeLimitSeconds) {
                            System.out.println("✓ 第${round + 1}轮分配后时间限制达标（超过${timeLimitHours}小时），立即停止分配")
                            shouldStopRound = true
                            continueAllocation = false
                            break
                        }
                    }
                } else {
                    System.out.println("第${round + 1}轮符文 $rune 无法分配菜谱（所有厨师都已达到3道菜谱限制）")
                }
                
                System.out.println("")
            }
            
            round++
            
            // 检查是否所有厨师都达到3道菜谱限制
            val allChefsAtLimit = bestChefGroup.chefGroup.all { chef ->
                val chefRecipeCount = allocatedRecipes.count { it.assignedChef.chefId == chef.chefId }
                chefRecipeCount >= 3
            }
            
            if (allChefsAtLimit) {
                System.out.println("所有厨师都达到3道菜谱限制，停止分配")
                continueAllocation = false
                break
            }
            
            // 如果所有符文都无法分配菜谱，则停止
            val allRunesAssigned = selectedRunes.all { rune ->
                val runeRecipes = recipesByRune[rune] ?: emptyList()
                runeRecipes.any { recipe ->
                    !allocatedRecipes.any { it.recipe.name == recipe.name }
                }
            }
            
            if (!allRunesAssigned) {
                System.out.println("所有符文都无法继续分配菜谱，停止分配")
                continueAllocation = false
            }
        }
        
        System.out.println("=== 最终分配结果 ===")
        System.out.println("总轮次: $round")
        val finalTotalTimeFormatted = formatTime(totalCookingTime)
        val timeLimitFormatted = formatTime(timeLimitSeconds)
        System.out.println("总制作时间: ${totalCookingTime}秒${finalTotalTimeFormatted} (${String.format("%.1f", totalCookingTime / 3600.0)}小时)")
        System.out.println("时间限制: ${timeLimitSeconds}秒${timeLimitFormatted} (${timeLimitHours}小时)")
        
        if (round > maxRounds) {
            System.out.println("⚠️ 达到最大轮次限制(${maxRounds}轮)，强制停止分配")
        } else if (totalCookingTime >= timeLimitSeconds) {
            System.out.println("✓ 最终时间限制达标（超过${timeLimitHours}小时）")
        } else {
            System.out.println("✗ 最终时间限制仍未达标（未超过${timeLimitHours}小时）")
        }
        
        // 在最终分配结果确定后，为有神级料理技能的厨师补充菜谱
        System.out.println("=== 检查神级料理技能厨师菜谱补充 ===")
        System.out.println("检查厨师组: ${bestChefGroup.chefGroup.map { "${it.name}(${if (it.got) "已拥有" else "未拥有"})" }}")
        System.out.println("当前已分配菜谱数量: ${allocatedRecipes.size}")
        
        // 强制检查所有厨师，不管是否参与了主分配
        val supplementedRecipes = supplementDivineSkillChefRecipes(allocatedRecipes, bestChefGroup.chefGroup, enhancedChefs, skills, gameData)
        if (supplementedRecipes.isNotEmpty()) {
            System.out.println("✓ 成功补充 ${supplementedRecipes.size} 道强补菜谱")
            supplementedRecipes.forEach { recipe ->
                System.out.println("  - 强补菜谱: ${recipe.recipe.name} -> 厨师 ${recipe.assignedChef.name} (品级:${recipe.quality}, 份数:${recipe.quantity})")
            }
            // 将补充的菜谱添加到总分配结果中
            allocatedRecipes.addAll(supplementedRecipes)
            System.out.println("补充后总菜谱数量: ${allocatedRecipes.size}")
        } else {
            System.out.println("✓ 无需补充菜谱")
        }
        
        // 创建分配结果
        return RecipeAllocationResult(
            chefGroup = bestChefGroup.chefGroup,
            allocatedRecipes = allocatedRecipes,
            totalCookingTime = totalCookingTime,
            totalGuestRate = bestChefGroup.totalGuestRate,
            totalCritRate = bestChefGroup.totalCritRate,
            totalTimeBonus = bestChefGroup.totalTimeBonus,
            unitTime = bestChefGroup.unitTime,
            hundredPotOutput = bestChefGroup.hundredPotOutput,
            unitFood = bestChefGroup.unitFood
        )
    }
}

/**
 * 获取贵客率对照表数据
 * @return 贵客率-份数对照表
 */
private fun getGuestPortionTable(): Map<Int, Map<Int, Int>> {
    return mapOf(
        // 贵客率从80%到540%，对应1-5星菜谱的份数
        80 to mapOf(1 to 59, 2 to 39, 3 to 42, 4 to 91, 5 to 62),
        90 to mapOf(1 to 57, 2 to 38, 3 to 40, 4 to 86, 5 to 59),
        100 to mapOf(1 to 55, 2 to 36, 3 to 39, 4 to 81, 5 to 56),
        110 to mapOf(1 to 53, 2 to 35, 3 to 37, 4 to 77, 5 to 53),
        120 to mapOf(1 to 52, 2 to 34, 3 to 36, 4 to 73, 5 to 50),
        130 to mapOf(1 to 50, 2 to 33, 3 to 34, 4 to 69, 5 to 48),
        140 to mapOf(1 to 49, 2 to 32, 3 to 33, 4 to 66, 5 to 46),
        150 to mapOf(1 to 47, 2 to 31, 3 to 32, 4 to 63, 5 to 44),
        160 to mapOf(1 to 46, 2 to 31, 3 to 31, 4 to 60, 5 to 42),
        170 to mapOf(1 to 45, 2 to 30, 3 to 30, 4 to 57, 5 to 40),
        180 to mapOf(1 to 44, 2 to 29, 3 to 30, 4 to 55, 5 to 38),
        190 to mapOf(1 to 43, 2 to 29, 3 to 29, 4 to 52, 5 to 37),
        200 to mapOf(1 to 42, 2 to 28, 3 to 28, 4 to 50, 5 to 36),
        210 to mapOf(1 to 41, 2 to 28, 3 to 27, 4 to 48, 5 to 34),
        220 to mapOf(1 to 41, 2 to 27, 3 to 27, 4 to 46, 5 to 33),
        230 to mapOf(1 to 40, 2 to 27, 3 to 26, 4 to 45, 5 to 32),
        240 to mapOf(1 to 39, 2 to 26, 3 to 26, 4 to 43, 5 to 31),
        250 to mapOf(1 to 39, 2 to 26, 3 to 25, 4 to 41, 5 to 30),
        260 to mapOf(1 to 38, 2 to 25, 3 to 25, 4 to 40, 5 to 29),
        270 to mapOf(1 to 37, 2 to 25, 3 to 24, 4 to 39, 5 to 28),
        280 to mapOf(1 to 37, 2 to 25, 3 to 24, 4 to 37, 5 to 27),
        290 to mapOf(1 to 36, 2 to 24, 3 to 23, 4 to 36, 5 to 26),
        300 to mapOf(1 to 36, 2 to 24, 3 to 23, 4 to 35, 5 to 25),
        310 to mapOf(1 to 35, 2 to 24, 3 to 23, 4 to 34, 5 to 25),
        320 to mapOf(1 to 35, 2 to 23, 3 to 22, 4 to 33, 5 to 24),
        330 to mapOf(1 to 35, 2 to 23, 3 to 22, 4 to 32, 5 to 23),
        340 to mapOf(1 to 34, 2 to 23, 3 to 22, 4 to 31, 5 to 23),
        350 to mapOf(1 to 34, 2 to 23, 3 to 21, 4 to 30, 5 to 22),
        360 to mapOf(1 to 33, 2 to 22, 3 to 21, 4 to 29, 5 to 22),
        370 to mapOf(1 to 33, 2 to 22, 3 to 21, 4 to 28, 5 to 21),
        380 to mapOf(1 to 33, 2 to 22, 3 to 20, 4 to 27, 5 to 20),
        390 to mapOf(1 to 32, 2 to 22, 3 to 20, 4 to 26, 5 to 20),
        400 to mapOf(1 to 32, 2 to 21, 3 to 20, 4 to 26, 5 to 19),
        410 to mapOf(1 to 32, 2 to 21, 3 to 20, 4 to 25, 5 to 19),
        420 to mapOf(1 to 31, 2 to 21, 3 to 19, 4 to 24, 5 to 18),
        430 to mapOf(1 to 31, 2 to 21, 3 to 19, 4 to 23, 5 to 18),
        440 to mapOf(1 to 31, 2 to 21, 3 to 19, 4 to 23, 5 to 18),
        450 to mapOf(1 to 31, 2 to 21, 3 to 19, 4 to 22, 5 to 17),
        460 to mapOf(1 to 30, 2 to 20, 3 to 18, 4 to 22, 5 to 17),
        470 to mapOf(1 to 30, 2 to 20, 3 to 18, 4 to 21, 5 to 16),
        480 to mapOf(1 to 30, 2 to 20, 3 to 18, 4 to 20, 5 to 16),
        490 to mapOf(1 to 30, 2 to 20, 3 to 18, 4 to 20, 5 to 16),
        500 to mapOf(1 to 29, 2 to 20, 3 to 18, 4 to 19, 5 to 15),
        510 to mapOf(1 to 29, 2 to 20, 3 to 18, 4 to 19, 5 to 15),
        520 to mapOf(1 to 29, 2 to 20, 3 to 17, 4 to 18, 5 to 15),
        530 to mapOf(1 to 29, 2 to 19, 3 to 17, 4 to 18, 5 to 14),
        540 to mapOf(1 to 29, 2 to 19, 3 to 17, 4 to 17, 5 to 14)
    )
}

/**
 * 根据贵客率和星级获取必来份数
 * @param totalGuestRate 总贵客率
 * @param starLevel 菜谱星级 (1-5)
 * @return 必来份数
 */
private fun getRequiredPortionsForStarLevel(totalGuestRate: Double, starLevel: Int): Int {
    val guestPortionTable = getGuestPortionTable()
    
    // 找到最接近的贵客率
    val closestRate = guestPortionTable.keys.minByOrNull { rate ->
        kotlin.math.abs(rate - totalGuestRate)
    } ?: 80
    
    // 获取该贵客率下对应星级的份数
    return guestPortionTable[closestRate]?.get(starLevel) ?: 0
}

/**
 * 根据份数和星级获取所需贵客率
 * @param portions 份数
 * @param starLevel 菜谱星级 (1-5)
 * @return 所需贵客率
 */
private fun getRequiredGuestRateForStarLevel(portions: Int, starLevel: Int): Double {
    val guestPortionTable = getGuestPortionTable()
    
    // 找到最接近的份数
    val closestRate = guestPortionTable.entries.minByOrNull { (_, starData) ->
        val targetPortions = starData[starLevel] ?: 0
        if (targetPortions == 0) Int.MAX_VALUE else kotlin.math.abs(targetPortions - portions)
    }?.key ?: 80.0
    
    return closestRate.toDouble()
}

/**
 * 根据份数获取菜谱星级
 * @param portions 份数
 * @return 菜谱星级
 */
private fun getRecipeStarLevel(portions: Int): Int {
    return when (portions) {
        in 14..24 -> 5 // 5星菜谱份数范围
        in 18..22 -> 4 // 4星菜谱份数范围
        in 15..18 -> 3 // 3星菜谱份数范围
        in 12..16 -> 2 // 2星菜谱份数范围
        in 8..12 -> 1  // 1星菜谱份数范围
        else -> 5 // 默认5星
    }
}

/**
 * 根据份数获取菜谱星级中文文本
 * @param portions 份数
 * @return 菜谱星级中文文本
 */
private fun getRecipeStarLevelText(portions: Int): String {
    return when (portions) {
        in 14..24 -> "五星" // 5星菜谱份数范围
        in 18..22 -> "四星" // 4星菜谱份数范围
        in 15..18 -> "三星" // 3星菜谱份数范围
        in 12..16 -> "二星" // 2星菜谱份数范围
        in 8..12 -> "一星"  // 1星菜谱份数范围
        else -> "五星" // 默认五星
    }
}



/**
 * 分析星级菜谱限制
 * @param recipes 菜谱列表
 * @param totalGuestRate 总贵客率
 * @param recipeLimits 个人菜谱上限
 * @return 星级限制信息列表
 */
private fun analyzeStarLevelLimits(
    recipes: List<com.example.show_auto.data.Recipe>,
    totalGuestRate: Double,
    recipeLimits: com.example.show_auto.ui.pages.RecipeLimitsState
): List<StarLevelLimit> {
    val starLimits = mutableListOf<StarLevelLimit>()
    
    // 按星级分组分析
    val recipesByStar = recipes.groupBy { it.rarity }
    
    recipesByStar.forEach { (starLevel, starRecipes) ->
        // 计算该星级菜谱在当前贵客率下需要的份数
        val requiredPortions = getRequiredPortionsForStarLevel(totalGuestRate, starLevel)
        
        // 计算该星级菜谱的个人上限
        val personalLimit = when (starLevel) {
            5 -> 15 + recipeLimits.star5
            4 -> 20 + recipeLimits.star4
            3 -> 25 + recipeLimits.star3
            2 -> 30 + recipeLimits.star2
            1 -> 40 + recipeLimits.star1
            else -> 40 + recipeLimits.star1
        }
        
        // 如果需要的份数超过个人上限，则添加到限制列表
        if (requiredPortions > personalLimit) {
            // 计算需要多少贵客率才能达到个人上限
            val requiredGuestRate = getRequiredGuestRateForStarLevel(personalLimit, starLevel)
            
            starLimits.add(
                StarLevelLimit(
                    starLevel = starLevel,
                    personalLimit = personalLimit,
                    requiredPortions = requiredPortions,
                    requiredGuestRate = requiredGuestRate
                )
            )
        }
    }
    
    return starLimits
}

/**
 * 计算单个菜谱的最大份数
 * @param recipe 菜谱
 * @param recipeLimits 个人菜谱上限
 * @return 最大份数
 */
private fun calculateMaxRecipePortions(recipe: Recipe, recipeLimits: com.example.show_auto.ui.pages.RecipeLimitsState): Int {
    // 基础份数
    val basePortions = when (recipe.rarity) {
        1 -> 40
        2 -> 30
        3 -> 25
        4 -> 20
        5 -> 15
        else -> 0
    }
    
    // 个人上限加成
    val limitBonus = when (recipe.rarity) {
        1 -> recipeLimits.star1
        2 -> recipeLimits.star2
        3 -> recipeLimits.star3
        4 -> recipeLimits.star4
        5 -> recipeLimits.star5
        else -> 0
    }
    
    return basePortions + limitBonus
}

/**
 * 检查厨师是否有开业时间相关技能（独立函数）
 */
private fun hasOpeningTimeSkillForQuery(chef: com.example.show_auto.data.Chef, skills: List<com.example.show_auto.data.Skill>, defaultAllUltimate: Boolean = false): Boolean {
    // 获取基础技能和修炼技能描述
    val baseSkillDesc = if (chef.skill > 0) {
        skills.find { it.skillId == chef.skill }?.desc ?: ""
    } else {
        ""
    }
    val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(chef, skills, defaultAllUltimate)
    val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
    
    // 检查是否包含开业时间相关技能
    val openingTimePatterns = listOf(
        "开业时间\\+(\\d+(?:\\.\\d+)?)%",
        "开业时间-(\\d+(?:\\.\\d+)?)%"
    )
    
    return openingTimePatterns.any { pattern ->
        pattern.toRegex().find(combinedSkillDesc) != null
    }
}



/**
 * 获取所有符合条件的厨师
 * @param gameData 游戏数据
 * @param skills 技能数据
 * @param personalData 个人数据
 * @param settingsStorage 设置存储
 * @return 符合条件的厨师列表
 */
private fun getAllQualifiedChefs(
    gameData: com.example.show_auto.data.GameData,
    skills: List<com.example.show_auto.data.Skill>,
    personalData: com.example.show_auto.data.PersonalData?,
    settingsStorage: com.example.show_auto.data.SettingsStorage
): List<com.example.show_auto.data.Chef> {
    System.out.println("getAllQualifiedChefs 函数被调用")
    System.out.println("总厨师数量: ${gameData.chefs.size}")
    
    // 从设置中读取筛选条件
    val onlyShowOwned = settingsStorage.getCalculatorOnlyShowOwned()
    val onlyShowUltimateChefs = settingsStorage.getCalculatorOnlyShowUltimateChefs()
    val onlyShowAssassinChefs = settingsStorage.getCalculatorOnlyShowAssassinChefs()
    
    System.out.println("筛选条件: onlyShowOwned=$onlyShowOwned, onlyShowUltimateChefs=$onlyShowUltimateChefs, onlyShowAssassinChefs=$onlyShowAssassinChefs")
    
    // 应用筛选条件
    val filteredChefs = gameData.chefs.filter { chef ->
        // 基础筛选：是否只显示已拥有的厨师
        val ownershipFilter = !onlyShowOwned || chef.got
        
        // 修炼状态筛选
        val cultivationFilter = when {
            onlyShowUltimateChefs && onlyShowAssassinChefs -> true // 两个都开启：显示所有厨师
            onlyShowUltimateChefs -> chef.ult // 只开启"查询已修"：只显示已修炼厨师
            onlyShowAssassinChefs -> hasOpeningTimeSkillForQuery(chef, skills, settingsStorage.getCalculatorDefaultAllUltimate()) // 只开启"查询刺客"：只显示有开业时间技能的厨师
            else -> true // 两个都不开启：显示所有厨师
        }
        
        // 贵客厨师筛选（默认开启）
        val auraFilter = isAuraChef(chef, skills)
        
        val result = ownershipFilter && cultivationFilter && auraFilter
        if (result) {
            // 获取该厨师当前佩戴的厨具
            val chefEquip = if (personalData != null && gameData != null) {
                val equipId = personalData.chefs[chef.chefId]?.equip
                if (equipId != null) {
                    gameData.equips.find { it.equipId == equipId.toString() }
                } else {
                    null
                }
            } else {
                null
            }
            
            // 获取该厨师的预计算好的加成数据（与厨师选择对话框使用相同的计算逻辑）
            // 注意：这里需要传入心法盘默认满级设置和默认全修炼设置，而不是硬编码的false
            val guestRateBonus = calculateTotalGuestRateBonusWithMaxAmber(chef, skills, gameData, personalData, settingsStorage.getCalculatorDefaultMaxLevelAmber(), settingsStorage.getCalculatorDefaultAllUltimate())
            // 使用与主界面相同的暴击率计算函数，确保结果一致
            val critRateBonus = calculateTotalCritRateForCalculator(chef, skills, gameData, personalData, settingsStorage.getCalculatorDefaultAllUltimate()) - 100.0
            val timeBonus = calculateOpeningTimeBonus(chef, chefEquip, skills, gameData, personalData, settingsStorage.getCalculatorDefaultAllUltimate())
            
            System.out.println("厨师 ${chef.name} 通过筛选 - 总贵客率:${String.format("%.2f", guestRateBonus)}%, 总暴击率:${String.format("%.2f", critRateBonus)}%, 开业时间:${String.format("%.2f", timeBonus)}%")
        }
        
        result
    }
    
    System.out.println("筛选后厨师数量: ${filteredChefs.size}")
    
    // 排序
    val sortedChefs = filteredChefs.sortedWith { chef1, chef2 ->
        // 按星级降序，再按贵客率降序排序
        val rarityComparison = chef2.rarity.compareTo(chef1.rarity)
        if (rarityComparison != 0) {
            rarityComparison
        } else {
            val guestRate1 = calculateTotalGuestRateBonusWithMaxAmber(chef1, skills, gameData, personalData, false)
            val guestRate2 = calculateTotalGuestRateBonusWithMaxAmber(chef2, skills, gameData, personalData, false)
            guestRate2.compareTo(guestRate1)
        }
    }
    
    System.out.println("排序完成，返回 ${sortedChefs.size} 个厨师")
    return sortedChefs
}

/**
 * 使用现有的查询逻辑查询厨师
 */
private fun getChefsByExistingLogic(
    gameData: com.example.show_auto.data.GameData,
    skills: List<com.example.show_auto.data.Skill>,
    personalData: com.example.show_auto.data.PersonalData?,
    settingsStorage: com.example.show_auto.data.SettingsStorage,
    onlyShowOwned: Boolean,
    onlyShowCritChefs: Boolean,
    onlyShowAssassinChefs: Boolean,
    defaultMaxLevelAmber: Boolean = false
): List<com.example.show_auto.data.Chef> {
    System.out.println("getChefsByExistingLogic 函数被调用 - 使用现有查询逻辑")
    System.out.println("查询条件: onlyShowOwned=$onlyShowOwned, onlyShowCritChefs=$onlyShowCritChefs, onlyShowAssassinChefs=$onlyShowAssassinChefs")
    
    // 直接使用现有的查询逻辑，与 CalculatorChefSelectionDialog 中的逻辑完全一致
    val filteredChefs = gameData.chefs.filter { chef ->
        // 搜索匹配（这里不需要搜索，所以总是true）
        val searchMatches = true
        
        // 贵客厨师筛选（默认开启）
        val auraMatches = isAuraChef(chef, skills)
        
        // 暴击厨师筛选
        val critMatches = if (onlyShowCritChefs) {
            hasCritSkill(chef, skills, settingsStorage.getCalculatorDefaultAllUltimate()) // 只显示有暴击技能的厨师
        } else {
            true
        }

        // 修炼状态筛选 - 修复逻辑：当两个都开启时显示所有厨师
        val cultivationMatches = when {
            false && onlyShowAssassinChefs -> true // 两个都开启：显示所有厨师
            false -> true // 不限制修炼状态，显示所有厨师
            onlyShowAssassinChefs -> hasOpeningTimeSkillForQuery(chef, skills, settingsStorage.getCalculatorDefaultAllUltimate()) // 只开启"查询刺客"：只显示有开业时间技能的厨师
            else -> true // 两个都不开启：显示所有厨师
        }

        (!onlyShowOwned || chef.got) && // 是否只显示已拥有的厨师
        searchMatches && auraMatches && critMatches && cultivationMatches
    }
    
    System.out.println("筛选后厨师数量: ${filteredChefs.size}")
    
    // 排序逻辑，与 CalculatorChefSelectionDialog 中的逻辑完全一致
    val sortedChefs = filteredChefs.sortedWith { chef1, chef2 ->
        // 如果开启了查询暴击，按照星级降序、暴击降序、贵客率降序排序
        if (onlyShowCritChefs) {
            // 首先按星级降序排序（高星级优先）
            val rarityComparison = chef2.rarity.compareTo(chef1.rarity)
            if (rarityComparison != 0) {
                rarityComparison
            } else {
                // 同星级内，按总暴击率降序排序
                val critRate1 = calculateTotalCritRate(chef1, skills, gameData, personalData, settingsStorage.getCalculatorDefaultAllUltimate())
                val critRate2 = calculateTotalCritRate(chef2, skills, gameData, personalData, settingsStorage.getCalculatorDefaultAllUltimate())
                val critRateComparison = critRate2.compareTo(critRate1)
                if (critRateComparison != 0) {
                    critRateComparison
                } else {
                    // 暴击率相同时，按总贵客率降序排序
                    val guestRate1 = calculateTotalGuestRateBonusWithMaxAmber(chef1, skills, gameData, personalData, defaultMaxLevelAmber, settingsStorage.getCalculatorDefaultAllUltimate())
                    val guestRate2 = calculateTotalGuestRateBonusWithMaxAmber(chef2, skills, gameData, personalData, defaultMaxLevelAmber, settingsStorage.getCalculatorDefaultAllUltimate())
                    guestRate2.compareTo(guestRate1)
                }
            }
        } else if (onlyShowAssassinChefs) {
            // 查询刺客模式：按贵客率降序、暴击率降序、时间降序排序
            val guestRate1 = calculateTotalGuestRateBonusWithMaxAmber(chef1, skills, gameData, personalData, defaultMaxLevelAmber, settingsStorage.getCalculatorDefaultAllUltimate())
            val guestRate2 = calculateTotalGuestRateBonusWithMaxAmber(chef2, skills, gameData, personalData, defaultMaxLevelAmber, settingsStorage.getCalculatorDefaultAllUltimate())
            val guestRateComparison = guestRate2.compareTo(guestRate1)
            if (guestRateComparison != 0) {
                guestRateComparison
            } else {
                // 贵客率相同时，按总暴击率降序排序
                val critRate1 = calculateTotalCritRate(chef1, skills, gameData, personalData, settingsStorage.getCalculatorDefaultAllUltimate())
                val critRate2 = calculateTotalCritRate(chef2, skills, gameData, personalData, settingsStorage.getCalculatorDefaultAllUltimate())
                val critRateComparison = critRate2.compareTo(critRate1)
                if (critRateComparison != 0) {
                    critRateComparison
                } else {
                    // 暴击率相同时，按开业时间技能降序排序（时间越短越好）
                    val time1 = calculateOpeningTimeBonus(chef1, null, skills, gameData, personalData, settingsStorage.getCalculatorDefaultAllUltimate())
                    val time2 = calculateOpeningTimeBonus(chef2, null, skills, gameData, personalData, settingsStorage.getCalculatorDefaultAllUltimate())
                    time1.compareTo(time2) // 时间越短越好，所以是升序
                }
            }
        } else {
            // 默认排序逻辑：先按星级降序，再按总贵客率降序，最后按暴击率降序
            val rarityComparison = chef2.rarity.compareTo(chef1.rarity)
            if (rarityComparison != 0) {
                rarityComparison
            } else {
                // 同星级内，按总贵客率降序排序
                val guestRate1 = calculateTotalGuestRateBonusWithMaxAmber(chef1, skills, gameData, personalData, defaultMaxLevelAmber, settingsStorage.getCalculatorDefaultAllUltimate())
                val guestRate2 = calculateTotalGuestRateBonusWithMaxAmber(chef2, skills, gameData, personalData, defaultMaxLevelAmber, settingsStorage.getCalculatorDefaultAllUltimate())
                val guestRateComparison = guestRate2.compareTo(guestRate1)
                if (guestRateComparison != 0) {
                    guestRateComparison
                } else {
                    // 贵客率相同时，按总暴击率降序排序
                    val critRate1 = calculateTotalCritRate(chef1, skills, gameData, personalData, settingsStorage.getCalculatorDefaultAllUltimate())
                    val critRate2 = calculateTotalCritRate(chef2, skills, gameData, personalData, settingsStorage.getCalculatorDefaultAllUltimate())
                    critRate2.compareTo(critRate1)
                }
            }
        }
    }
    
    System.out.println("排序完成，返回 ${sortedChefs.size} 个厨师")
    return sortedChefs
}

/**
 * 检查厨师是否具有暴击相关技能（独立函数）
 */
private fun hasCritSkill(chef: com.example.show_auto.data.Chef, skills: List<com.example.show_auto.data.Skill>, defaultAllUltimate: Boolean = false): Boolean {
    // 获取基础技能和修炼技能描述
    val baseSkillDesc = if (chef.skill > 0) {
        skills.find { it.skillId == chef.skill }?.desc ?: ""
    } else {
        ""
    }
    val ultimateSkillDesc = getChefSkillDescriptionForCalculationWithOverride(chef, skills, defaultAllUltimate)
    val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
    
    // 检查是否包含暴击相关技能模式（与 CalculatorChefSelectionDialog 中的逻辑一致）
    val critPatterns = listOf(
        "稀有客人赠礼数量\\d+%概率提升\\d+%", // 稀有客人赠礼数量X%概率提升X%
        "每制作一种神级料理贵客赠礼翻倍概率\\+\\d+(?:\\.\\d+)?%", // 每制作一道神级每制作一种神级料理贵客赠礼翻倍概率料理贵客率赠礼翻倍概率+*%
        "贵客赠礼数量\\d+%概率提升\\d+%" // 贵客赠礼数量*%概率提升*%
    )
    
    return critPatterns.any { pattern ->
        pattern.toRegex().find(combinedSkillDesc) != null
    }
}

/**
 * 符文项目组件
 */
@Composable
private fun RuneItem(
    rune: String,
    isSelected: Boolean,
    onToggle: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 8.dp, horizontal = 12.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        // 符文名称
        Text(
            text = rune,
            fontSize = 14.sp,
            fontWeight = FontWeight.Medium,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
            modifier = Modifier.weight(1f)
        )
        
        // 选择按钮
        Checkbox(
            checked = isSelected,
            onCheckedChange = { onToggle() },
            colors = CheckboxDefaults.colors(
                checkedColor = Color(0xFF4CAF50),
                uncheckedColor = Color(0xFFCCCCCC)
            ),
            modifier = Modifier.size(20.dp)
        )
    }
}

/**
 * 符文项目组件
 */
@Composable
private fun RuneItemWithRecipeCount(
    rune: String,
    isSelected: Boolean,
    recipeCount: Int,
    onToggle: () -> Unit,
    onRecipeCountChange: (Int) -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 8.dp, horizontal = 12.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        // 符文名称
        Text(
            text = rune,
            fontSize = 14.sp,
            fontWeight = FontWeight.Medium,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
            modifier = Modifier.weight(1f)
        )
        
        // 选择按钮
        Checkbox(
            checked = isSelected,
            onCheckedChange = { onToggle() },
            colors = CheckboxDefaults.colors(
                checkedColor = Color(0xFF4CAF50),
                uncheckedColor = Color(0xFFCCCCCC)
            ),
            modifier = Modifier.size(20.dp)
        )
    }
}

/**
 * 符文卡片组件 - 淡蓝色背景
 */
@Composable
private fun RuneCard(
    rune: String,
    isSelected: Boolean,
    onToggle: () -> Unit,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .fillMaxWidth()
            .clickable { onToggle() },
        colors = CardDefaults.cardColors(
            containerColor = Color(0xFFE3F2FD) // 淡蓝色背景
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        shape = RoundedCornerShape(8.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(12.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 符文名称
            Text(
                text = rune,
                fontSize = 14.sp,
                fontWeight = FontWeight.Medium,
                color = MaterialTheme.colorScheme.onSurface,
                modifier = Modifier.weight(1f)
            )
            
            // 选择框
            Checkbox(
                checked = isSelected,
                onCheckedChange = { onToggle() },
                colors = CheckboxDefaults.colors(
                    checkedColor = Color(0xFF1976D2), // 深蓝色选中状态
                    uncheckedColor = Color(0xFF757575) // 灰色未选中状态
                ),
                modifier = Modifier.size(20.dp)
            )
        }
    }
}

/**
 * 自定义开关组件 - 更小的尺寸
 */
@Composable
private fun CustomSwitch(
    checked: Boolean,
    onCheckedChange: (Boolean) -> Unit,
    modifier: Modifier = Modifier,
    alwaysOn: Boolean = false // 新增参数：是否始终显示开启状态
) {
    Box(
        modifier = modifier
            .clickable { onCheckedChange(!checked) }
            .background(
                color = if (alwaysOn) MaterialTheme.colorScheme.primary else if (checked) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline,
                shape = RoundedCornerShape(9.dp)
            ),
        contentAlignment = Alignment.Center
    ) {
        Box(
            modifier = Modifier
                .size(14.dp)
                .offset(
                    x = if (checked) 8.dp else (-8).dp
                )
                .background(
                    color = MaterialTheme.colorScheme.onPrimary,
                    shape = RoundedCornerShape(7.dp)
                )
        )
    }
}

/**
 * 成功提示弹窗 - 参考采集编队页面的样式
 */
@Composable
private fun SaveSuccessDialog(
    message: String = "保存成功",
    onDismiss: () -> Unit
) {
    // 1秒后自动消失
    LaunchedEffect(Unit) {
        delay(1000)
        onDismiss()
    }
    
    Dialog(
        onDismissRequest = onDismiss,
        properties = WindowDialogProperties(
            dismissOnBackPress = false,
            dismissOnClickOutside = false
        )
    ) {
        Card(
            modifier = Modifier
                .wrapContentSize()
                .padding(16.dp),
            colors = CardDefaults.cardColors(
                containerColor = Color(0xFFFCE4EC) // 淡红色背景
            ),
            elevation = CardDefaults.cardElevation(defaultElevation = 8.dp),
            shape = RoundedCornerShape(12.dp)
        ) {
            Row(
                modifier = Modifier.padding(16.dp),
                horizontalArrangement = Arrangement.Center,
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 警告图标
                Box(
                    modifier = Modifier
                        .size(32.dp)
                        .background(
                            color = Color(0xFFF44336),
                            shape = CircleShape
                        ),
                    contentAlignment = Alignment.Center
                ) {
                    Icon(
                        imageVector = Icons.Default.Close,
                        contentDescription = "警告",
                        tint = Color.White,
                        modifier = Modifier.size(18.dp)
                    )
                }
                
                Spacer(modifier = Modifier.width(12.dp))
                
                // 提示文字
                Text(
                    text = message,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Medium,
                    color = Color(0xFFD32F2F)
                )
            }
        }
    }
}






/**
 * 将秒数格式化为时分秒格式
 * @param seconds 秒数
 * @return 格式化的时间字符串，如 "1小时2分3秒"
 */
private fun formatTime(seconds: Int): String {
    if (seconds == 0) {
        return "0"
    }
    
    val hours = seconds / 3600
    val minutes = (seconds % 3600) / 60
    val remainingSeconds = seconds % 60
    
    return when {
        hours > 0 -> "${hours}小时${minutes}分${remainingSeconds}秒"
        minutes > 0 -> "${minutes}分${remainingSeconds}秒"
        else -> "${remainingSeconds}秒"
    }
}

/**
 * 为有神级料理技能的厨师补充菜谱
 * @param allocatedRecipes 已分配的菜谱列表
 * @param chefGroup 厨师组
 * @param enhancedChefs 增强后的厨师列表
 * @param skills 技能列表
 * @param gameData 游戏数据
 * @return 补充的菜谱列表
 */
private fun supplementDivineSkillChefRecipes(
    allocatedRecipes: MutableList<AllocatedRecipe>,
    chefGroup: List<com.example.show_auto.data.Chef>,
    enhancedChefs: List<com.example.show_auto.data.Chef>,
    skills: List<com.example.show_auto.data.Skill>,
    gameData: com.example.show_auto.data.GameData?
): List<AllocatedRecipe> {
    val supplementedRecipes = mutableListOf<AllocatedRecipe>()
    
    // 检查每个厨师
    chefGroup.forEachIndexed { chefIndex, chef ->
        System.out.println("检查厨师 ${chef.name} (ID:${chef.chefId}, 拥有状态:${if (chef.got) "已拥有" else "未拥有"}) 的神级料理技能...")
        
        // 检查是否有神级料理技能
        val hasDivineSkill = hasDivineRecipeSkill(chef, skills)
        System.out.println("  神级料理技能检测结果: $hasDivineSkill")
        
        if (hasDivineSkill) {
            System.out.println("检查厨师 ${chef.name} 的神级料理技能菜谱补充...")
            
            // 计算该厨师已分配的菜谱数量
            val chefAllocatedCount = allocatedRecipes.count { it.assignedChef.chefId == chef.chefId }
            System.out.println("  厨师 ${chef.name} 已分配 $chefAllocatedCount 道菜谱")
            
            // 如果不足3道，需要补充
            if (chefAllocatedCount < 3) {
                val needSupplement = 3 - chefAllocatedCount
                System.out.println("  需要补充 $needSupplement 道菜谱")
                
                // 查询所有1星和2星菜谱
                val lowStarRecipes = gameData?.recipes?.filter { recipe ->
                    recipe.rarity in 1..2
                } ?: emptyList()
                
                System.out.println("  找到 ${lowStarRecipes.size} 道1-2星菜谱")
                
                // 筛选出该厨师能制作到神级的菜谱
                val divineQualityRecipes = mutableListOf<Pair<com.example.show_auto.data.Recipe, String>>()
                
                lowStarRecipes.forEach { recipe ->
                    val quality = calculateRecipeQuality(enhancedChefs[chefIndex], recipe)
                    if (quality == "神" || quality == "传") {
                        divineQualityRecipes.add(Pair(recipe, quality))
                        System.out.println("    ${recipe.name} (${recipe.rarity}星) -> 品级: $quality")
                    }
                }
                
                System.out.println("  其中 ${divineQualityRecipes.size} 道菜谱能达到神级")
                
                // 按时间升序排序
                val sortedRecipes = divineQualityRecipes.sortedBy { it.first.time }
                
                // 补充菜谱，直到达到3道或没有更多合适的菜谱
                var supplementedCount = 0
                for ((recipe, quality) in sortedRecipes) {
                    if (supplementedCount >= needSupplement) {
                        break
                    }
                    
                    // 检查该菜谱是否已被分配
                    val isAlreadyAllocated = allocatedRecipes.any { it.recipe.name == recipe.name }
                    if (!isAlreadyAllocated) {
                        // 创建强补菜谱，份数始终为1
                        val supplementedRecipe = AllocatedRecipe(
                            recipe = recipe,
                            assignedChef = chef,
                            rune = "", // 强补菜谱没有符文
                            quantity = 1, // 强补菜谱份数始终为1
                            cookingTime = recipe.time, // 单份时间
                            quality = quality,
                            isSupplemented = true // 标记为强补菜谱
                        )
                        
                        supplementedRecipes.add(supplementedRecipe)
                        supplementedCount++
                        
                        System.out.println("    ✓ 补充强补菜谱: ${recipe.name} (品级:$quality, 时间:${recipe.time}秒)")
                    }
                }
                
                if (supplementedCount > 0) {
                    System.out.println("  ✓ 厨师 ${chef.name} 成功补充 $supplementedCount 道强补菜谱")
                } else {
                    System.out.println("  ⚠️ 厨师 ${chef.name} 没有找到合适的强补菜谱")
                }
            } else {
                System.out.println("  厨师 ${chef.name} 已有3道菜谱，无需补充")
            }
        } else {
            System.out.println("  厨师 ${chef.name} 没有神级料理技能，跳过补充")
        }
    }
    
    return supplementedRecipes
}
